为什么JS允许变异const数组?
例如:
const a = 5
a = 6 //throws error
const arr = [1,2,3]
arr[2] = 4 // no error
为什么允许它变异一个const数组,因为它应该抛出一个错误,就像在第一种情况下一样?
还如何确保我的数组保持完全不可变?
发布于 2020-01-11 18:30:54
允许在JS中添加、删除或更改const数组,因为arr
变量存储内存引用而不是值。
因此,即使在那个内存位置操作值,也不会真正更改对内存的引用,因此变量仍然是const
。
唯一不允许的是重新分配数组arr = []
,这实际上意味着更改arr变量存储的内存引用。
正如@Nina所说,不允许向const变量分配任何类型的。
const arr = [1, 2, 3]
arr[2] = 4 //this is fine as memory reference is still the same
arr[3] = 3
console.log(arr)
arr = [] //throws error
console.log(arr)
发布于 2020-01-11 18:41:47
Javascript中的标量值按值存储。例如:
let a = "foo" <--- a is linked to the value "foo"
let b = "foo" <--- b is also linked to the value "foo"
对象和数组通过引用存储。例如:
const arr = [1,2,3] <--- arr is linked to a unique address in memory that references 1, 2, and 3
当数组或对象发生变异时,内存中的地址不需要更改:
arr.push(4) <-- arr is now [1,2,3,4], but its address in memory doesn't need to change, it's still just an array that references 1, 2, 3, and now 4
https://stackoverflow.com/questions/59697412
复制相似问题