javascript使用不可变字符串还是可变字符串?我需要一个“字符串生成器”吗?


当前回答

字符串是不可变的——它们不能改变,我们只能创造新的字符串。

例子:

var str= "Immutable value"; // it is immutable

var other= statement.slice(2, 10); // new string

其他回答

来自犀牛的书:

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

性能提示:

如果必须连接大字符串,请将字符串部分放入数组中,并使用array . join()方法获取整个字符串。这对于连接大量字符串来说可以快很多倍。

JavaScript中没有StringBuilder。

只是为了澄清像我这样头脑简单的人(来自MDN):

不可变对象是一旦对象被创建,其状态就不能改变的对象。 字符串和数字是不可变的。

不可变意味着:

你可以让一个变量名指向一个新的值,但是之前的值仍然保存在内存中。因此需要垃圾收集。 var immutableString = "Hello"; //在上面的代码中,创建了一个string值的新对象。 immutableString = immutableString + "World"; //我们现在将"World"附加到现有值。

这看起来像是我们在改变字符串'immutableString',但我们没有。而不是:

在给"immutableString"附加一个字符串值时,会发生以下事件: 检索"immutableString"的现有值 "World"被附加到"immutableString"的现有值 然后将结果值分配给一个新的内存块 "immutableString"对象现在指向新创建的内存空间 以前创建的内存空间现在可用于垃圾收集。

字符串是不可变的——它们不能改变,我们只能创造新的字符串。

例子:

var str= "Immutable value"; // it is immutable

var other= statement.slice(2, 10); // new string

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对象是可变的,但它包含的字符串类型值(基本类型)是不可变的。