Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

Is it possible to create a fixed length array in javascript?

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

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.

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.

question from:https://stackoverflow.com/questions/21988909/is-it-possible-to-create-a-fixed-length-array-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update:

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
}

Original Answer:

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 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); }


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...