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); }
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…