在 JavaScript 中更新常量数组

使用括号表示法来更新使用 const 关键字声明的数组的值,例如 arr[0] = ‘new value’。 使用 const 声明的数组元素可以直接更新,但不能重新分配变量。

const arr = ['hello', 'world'];

arr[0] = 'test';
console.log(arr); // ['test', 'world']

// ⛔️ Error: Assignment to constant variable.
arr = ['test', 'world'];

在 JavaScript 中更新常量数组

使用 const 关键字声明变量时,不能重新分配变量,但是如果变量是数组或对象,则可以直接更新其值。

// ✅ 正常运行
const arr = ['one']
arr[0] = 'two'
console.log(arr); // ?️ ['two']


const test = 'one'
// ⛔️️ Error: Assignment to constant variable.
test = 'two';

在 JavaScript 中更新常量数组

如果需要创建一个值不能改变的数组,可以使用 Object.freeze 方法。

const arr = ['apple', 'banana'];

Object.freeze(arr);

arr[0] = 'pear';
console.log(arr); // ?️ {country: 'Chile'}

Object.freeze 方法用于冻结数组或对象。

数组冻结后:

  • 它的元素不能改变
  • 新元素不能添加到数组中
  • 无法从数组中删除现有元素

结合使用 const 关键字和 Object.freeze 方法,使数组不可变。

最后,使用 const 关键字声明变量意味着不能重新分配变量,它不会使存储在变量中的值不可变。