【问题标题】:What do we mean by defining a const array in js? [duplicate]在 js 中定义一个 const 数组是什么意思? [复制]
【发布时间】:2020-08-14 10:49:08
【问题描述】:
当我们在javascript中将数组定义为常量时,是否意味着数组不能缩小或放大并且具有恒定的大小,或者是否意味着数组中的所有元素都是常量并且您无法更改它们的值。
handleClick(i) {
const squares = this.state.squares.slice();
squares[i] = 'X';
this.setState({squares: squares});
}
在上面的代码中。
【问题讨论】:
标签:
javascript
arrays
reactjs
【解决方案1】:
将变量声明为const 仅意味着一旦分配了值,您就无法为该变量分配新值:
const array = [];
array = []; // Not allowed: assignment to constant variable
将数组声明为 const 与您可以对实际数组的内容做什么无关:
const array = [];
array.push("something"); // Allowed: add value to array
array[0] = "or other"; // Allowed: replace value in array
array.length = 0; // Allowed: change array size