javascript使用不可变字符串还是可变字符串?我需要一个“字符串生成器”吗?
当前回答
string类型的值是不可变的,但是使用string()构造函数创建的string对象是可变的,因为它是一个对象,您可以向它添加新的属性。
> var str = new String("test")
undefined
> str
[String: 'test']
> str.newProp = "some value"
'some value'
> str
{ [String: 'test'] newProp: 'some value' }
同时,虽然您可以添加新的属性,但不能更改已经存在的属性
Chrome控制台测试的截图
总之, 1. 所有字符串类型值(基本类型)都是不可变的。 2. String对象是可变的,但它包含的字符串类型值(基本类型)是不可变的。
其他回答
字符串是不可变的——它们不能改变,我们只能创造新的字符串。
例子:
var str= "Immutable value"; // it is immutable
var other= statement.slice(2, 10); // new string
JavaScript字符串确实是不可变的。
Javascript中的字符串是不可变的
来自犀牛的书:
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings. Strings are assigned by reference, not by value. In general, when an object is assigned by reference, a change made to the object through one reference will be visible through all other references to the object. Because strings cannot be changed, however, you can have multiple references to a string object and not worry that the string value will change without your knowing it
string类型的值是不可变的,但是使用string()构造函数创建的string对象是可变的,因为它是一个对象,您可以向它添加新的属性。
> var str = new String("test")
undefined
> str
[String: 'test']
> str.newProp = "some value"
'some value'
> str
{ [String: 'test'] newProp: 'some value' }
同时,虽然您可以添加新的属性,但不能更改已经存在的属性
Chrome控制台测试的截图
总之, 1. 所有字符串类型值(基本类型)都是不可变的。 2. String对象是可变的,但它包含的字符串类型值(基本类型)是不可变的。