我已经在这个主题上进行了两周多的研究,我只是问一个问题,因为MDN's documentation on mutability说只有数组和对象不是原始值,当然,这是事实,它们有参考价值。
但是,我认为功能,字符串对象,日期和 RegEx 也具有参考值,因为它们也是非原语。
例如,如果我们在字符串原语上使用slice(),则javascript会自动将其转换(重新分配)为字符串对象,现在它是可变的,因为单词“ snow”通过重新分配而变成“ know”。这不适用于const
,因为它禁用了重新分配。
let word = 'snow'
console.log(word) // "snow"
word = `k${word.slice(1)}`
console.log(word) // "know"
所以我猜想MDN是错误的,还是dotnettricks之类的许多其他资源是错误的,甚至是一些javascript认证指南也是如此...
答案 0 :(得分:1)
MDN没错-函数,日期和RegEx 是对象。
此外,字符串仍然是原始的。
let a = 'snow';
let b = a;
a = 'know';
console.log(b); // snow
答案 1 :(得分:1)
“字符串”是原始的,而新的String(“ strings”)是一个对象,但是在两种情况下,字符序列都是不可变的。
在您的示例中,您并没有真正改变字符串,只是创建了一个新字符串并将其分配给相同的变量
var primitiveString = 'hello';
var objectString = new String('hello');
var objectStringRef = objectString;
// string are primitives so you can not add properties to it
primitiveString.newProperty = "my property";
console.log(primitiveString.newProperty) // undefined
// You can add properties to String objects
objectString.newProperty = "my property";
console.log(objectString.newProperty) // "my property"
// and you can have a reference to a String object
console.log(objectStringRef.newProperty) // "my property"
// but both are immutable
primitiveString[0] = "p";
objectString[0] = "p";
console.log(primitiveString) // "hello"
console.log(objectStringRef.toString()) // "hello"