I am trying to create a static array. But I found that it can increase the item in the array at run time. How I can achieve static array in JavaScript? Why array is mutable in JavaScript?
var a = [];
//var a = new Array(3);
for (var i = 0; i < 5; i++) {
//a.push(i);
a[i] = i;
}
document.write(a);
I am trying to create a static array. But I found that it can increase the item in the array at run time. How I can achieve static array in JavaScript? Why array is mutable in JavaScript?
var a = [];
//var a = new Array(3);
for (var i = 0; i < 5; i++) {
//a.push(i);
a[i] = i;
}
document.write(a);
Share
Improve this question
edited May 16, 2020 at 2:20
Penny Liu
17.4k5 gold badges86 silver badges108 bronze badges
asked Nov 2, 2016 at 18:02
Mohammad Arshad AlamMohammad Arshad Alam
9,8626 gold badges39 silver badges62 bronze badges
3
|
4 Answers
Reset to default 13You can freeze the array with Object.freeze
:
"use strict";
var a = Object.freeze([0, 1, 2]);
console.log(a);
try {
a.push(3); // Error
} catch (e) {
console.error(e);
}
try {
a[0] = "zero"; // Error
} catch (e) {
console.error(e);
}
console.log(a);
That disallows
- Changing existing properties, either their values or their other features like whether they're extensible, etc.
- Adding or removing properties
See the link for full details. If you just want to keep the size fixed but do want to allow changes to the values of entries, just use Object.seal
instead.
Note that whether attempts to change existing properties result in an error (as opposed to silent failure) depends on whether you're in strict mode.
freeze
and seal
were introduced in ES5 (June 2009), and so should be present in any vaguely up-to-date browser. Obsolete browsers will not have them.
Using the latest JS syntax (polyfill required for older browsers):
var list = Object.seal([1,2,3])
Object.seal prevents further changes to an Object.
It sounds like you want an immutable array.
Most languages have immutable collections, either built in or from a library. JS does not include them normally, but Facebook provides a library that holds all the typical immutable collection types.
While immutablejs does not have an array type as such, it does have the more traditional List
:
const staticArray = List([0, 1, 2, 3, 4]);
You can use Object.defineProperties()
to set writable:false
, configurable:false
at property descriptors, Object.preventExtensions()
to prevent new property being added to array or object.
"use strict";
const ro = obj => {
const props = {};
const length = obj.length || Object.keys(obj).length;
const entries = Array.isArray(obj)
? [...obj, length].entries()
: Array.from(Object.keys(obj), prop => [prop, obj[prop]]);
for (let [key, value] of entries) {
props[key === length ? `length` : key] = {
value: value,
configurable: false,
writable: false
}
}
return Object.preventExtensions(Object.defineProperties(obj, props));
};
let arr = ro([1,2,3]);
try {
console.log(`arr[0]:${arr[0]}`);
console.log(`try to set arr[0] to ${arr[0] = 4}`);
} catch (e) {
console.error(e)
}
try {
console.log(`try to .push() to arr ${arr.push(4)}`);
} catch (e) {
console.error(e)
}
try {
console.log(`try to set .length of arr ${arr.length = 4}`);
console.log(arr.length);
} catch (e) {
console.error(e)
}
try {
console.log(`try to delete of arr[1] ${delete arr[1]}`);
console.log(arr.length);
} catch (e) {
console.error(e)
}
console.log(JSON.stringify(arr, null, 2));
let obj = ro({a:1, b:2, c:3});
try {
console.log(`obj["c"]:${obj["c"]}`);
console.log(`try to assign 4 to obj["c"]:${obj["c"] = 4}`);
} catch (e) {
console.error(e)
}
try {
console.log(`try to assign property "d" to obj:${obj["d"] = 4}`);
} catch (e) {
console.error(e)
}
try {
console.log(`try to delete property "b" of obj:${delete obj["b"]}`);
} catch (e) {
console.error(e)
}
console.log(JSON.stringify(obj, null, 2));
.length
of the elements of the array should not be able to be increased after the array is initially defined? – guest271314 Commented Nov 2, 2016 at 18:05static
has a very specific meaning it most programming languages and its not this. It should be immutable. This is quite confusing for those coming here from google searches, looking for actual static arrays in js. I wont edit the title as this question is quite old. – Paul Rooney Commented May 31, 2023 at 22:24