简体   繁体   English

我们如何才能像具有Object.freeze()方法的对象那样使Javascript数组不可变?

[英]How can we make Javascript arrays immutable like for Objects we have Object.freeze() method?

For ex: 例如:

const arr = [1,2,3];
arr.push(4);    //4
console.log(arr) //[1,2,3,4]

I want this array to be immutable. 我希望这个数组是不可变的。 It should not allow push or add/delete arr values. 它不应允许推入或添加/删除arr值。

Object.freeze works just fine on arrays, since arrays are objects as well: Object.freeze在数组上也可以正常工作,因为数组也是对象:

 const arr = [1,2,3]; Object.freeze(arr); arr.push(4); // attempting to push throws 

Arrays are objects - so it'll work fine: 数组对象-因此可以正常工作:

 const arr = [1, 2, 3]; Object.freeze(arr); arr.push(4); arr[arr.length - 1] = 4; 

The index assignment method also fails: 索引分配方法也将失败:

 const arr = [1, 2, 3]; Object.freeze(arr); arr[arr.length - 1] = 4; 

Yes you can Freeze array 是的,您可以Freeze array

 const arr = [1,2,3]; Object.freeze(arr) arr.push(5); 

Note:- it will do shallow freeze, 注意:-它会进行浅层冻结,

 const arr = [1, 2, {key: 123}]; Object.freeze(arr) arr[2].key = 'changed value' console.log(arr) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM