是否可以在javascript中创建一个固定长度的数组? [英] Is it possible to create a fixed length array in javascript?

查看:1557
本文介绍了是否可以在javascript中创建一个固定长度的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,是否有可能创建一个长度保证保持不变的数组?

Is it possible, in Javascript, to create an array whose length is guaranteed to remain the same?

例如,数组A的长度为2。随后,任何调用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:

var a = new Array(42);
if(Object.seal) { 
  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:

var 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.

对于数组数字当然有类型数组

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆