const selectGroup = this.multipleSelection.find((map) => map.id === id)
if (selectGroup) {
selectGroup.quantity = currentValue
}
为何selectGroup
中quantity
的值可以被更改,const修饰不是不可以更改吗?
事实上,在 JavaScript
中,当你使用 const
声明一个变量时,你实际上是在声明一个对值的引用为常量的绑定,而不是值本身。换句话说,你不能重新分配 selectGroup
引用一个不同的对象或值,但你可以更改 selectGroup
对象的属性。
selectGroup.quantity = currentValue
这行代码更改了 selectGroup 对象的 quantity
属性。由于 selectGroup
是一个对象的引用,并且我们没有更改这个引用(即没有重新分配 selectGroup
到一个新的对象或值),所以这是允许的。
总之,const
在这里允许你声明一个对特定对象的引用,然后你可以更改该对象的属性,但不能重新分配 selectGroup
到另一个对象或值。这就是为什么即使使用了 const
,你也可以更改 selectGroup
对象的属性而不会导致错误。