为什么这个const可以变?

const a = {name:'tom'}
a.age = 16;

为什么这里可以变化?不会报错?

阅读 1.8k
2 个回答

const 对于数组和对象来说,只会确保引用不变。但内部的值可以被改变。

const arr = [];
arr.push(1);
arr[1] = 2;
console.log(arr); // [1, 2]

const obj = {};
obj.name = 'anran758'
console.log(obj); // {name: 'anran758'}

以上这种修改都是符合预期的。

首先你要了解值类型和引用类型的区别。

其次 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...
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题