首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >操作const数组

操作const数组
EN

Stack Overflow用户
提问于 2020-01-11 18:30:54
回答 2查看 835关注 0票数 0

为什么JS允许变异const数组?

例如:

代码语言:javascript
运行
复制
const a = 5
a = 6 //throws error

const arr = [1,2,3]
arr[2] = 4 // no error

为什么允许它变异一个const数组,因为它应该抛出一个错误,就像在第一种情况下一样?

还如何确保我的数组保持完全不可变?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-01-11 18:30:54

允许在JS中添加、删除或更改const数组,因为arr变量存储内存引用而不是值。

因此,即使在那个内存位置操作值,也不会真正更改对内存的引用,因此变量仍然是const

唯一不允许的是重新分配数组arr = [],这实际上意味着更改arr变量存储的内存引用。

正如@Nina所说,不允许向const变量分配任何类型的

代码语言:javascript
运行
复制
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)

票数 3
EN

Stack Overflow用户

发布于 2020-01-11 18:41:47

Javascript中的标量值按值存储。例如:

代码语言:javascript
运行
复制
let a = "foo" <--- a is linked to the value "foo"
let b = "foo" <--- b is also linked to the value "foo"

对象和数组通过引用存储。例如:

代码语言:javascript
运行
复制
const arr = [1,2,3] <--- arr is linked to a unique address in memory that references 1, 2, and 3

当数组或对象发生变异时,内存中的地址不需要更改:

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59697412

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档