是否可以在 javascript 中创建一个固定长度的数组? [英] Is it possible to create a fixed length array in javascript?
问题描述
是否可以在 Javascript 中创建一个长度保证保持不变的数组?
Is it possible, in Javascript, to create an array whose length is guaranteed to remain the same?
例如,创建长度为 2 的数组 A
.随后,任何尝试调用 A.push()
或 A.pop()
,或者设置A[5]
的值都会失败.A.length
永远是 2.
For example, the array A
is created with length 2. Subsequently, any attempt to call A.push()
or A.pop()
, or set the value of A[5]
will fail. A.length
will always be 2.
这是类型化数组(例如Float32Array
)的工作方式.它们有固定的尺寸.但我想要一种在常规数组上获得相同行为的方法.
This is the way that typed arrays (eg Float32Array
) already work. They have fixed size. But I want a way to get the same behaviour on a regular Array.
对于我的具体情况,我想创建一个固定长度的数组,其中每个条目都是一个对象.但我还是想知道一般问题的答案.
For my specific situation, I would like to create a fixed-length array where each entry is an object. But I would still like to know the answer to the general question.
推荐答案
更新:
Object.seal (这是 ES2015 的一部分)将做到这一点:
Object.seal (which is part of ES2015) will do just that:
// create array with 42 empty slots
let a = new Array(42);
if(Object.seal) {
// fill array with some value because
// empty slots can not be changed after calling Object.seal
a.fill(undefined);
Object.seal(a);
// now a is a fixed-size array with mutable entries
}
原答案:
差不多.正如 titusfx 所建议的那样,您可以冻结对象:
Almost. As was suggested by titusfx you can freeze the object:
let a = new Array(2);
// set values, e.g.
a[0] = { b: 0; }
a[1] = 0;
Object.freeze(a);
a.push(); // error
a.pop(); // error
a[1] = 42; // will be ignored
a[0].b = 42; // still works
但是,您无法更改冻结对象的值.如果您有一组对象,这可能不是问题,因为您仍然可以更改对象的值.
However you are unable to change the values of a freezed object. If you have an array of objects this may not be a problem since you can still change the values of the objects.
对于数字数组,当然有类型化数组.
For arrays of numbers there are of course typed arrays.
Object.freeze
是 ES2015 但大多数浏览器似乎都支持它,包括 IE9.您当然可以对其进行功能测试:
Object.freeze
is part of ES2015 but most browsers seem to support it, including IE9. You could of course feature-test it:
if(Object.freeze) { Object.freeze(obj);}
这篇关于是否可以在 javascript 中创建一个固定长度的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!