操作常量数组



为什么JS允许改变常量数组?

例如

const a = 5
a = 6 //throws error
const arr = [1,2,3]
arr[2] = 4 // no error

为什么允许在 const 数组应该像第一种情况一样抛出错误时对其进行变异?

另外,如何确保我的数组保持完全不可变?

允许在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)

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

最新更新