const a = {name:'tom'}
a.age = 16;
为什么这里可以变化?不会报错?
首先你要了解值类型和引用类型的区别。
其次 ES 规范中说的很明确了,The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.
简单记为 const
变量不可重新赋值就可以了,ES 中并没有什么 常量。
你这里并没有对变量 a
重新赋值,而只是修改了它的一个属性字段,所以不会报错。
https://developer.mozilla.org...
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
const
对于数组和对象来说,只会确保引用不变。但内部的值可以被改变。以上这种修改都是符合预期的。