Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create static array in JavaScript

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);
like image 615
Arshad Avatar asked Nov 02 '16 18:11

Arshad


People also ask

How can you create an array in JavaScript?

Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.

Can we declare array as static?

An array that is declared with the static keyword is known as static array. It allocates memory at compile-time whose size is fixed. We cannot alter the static array. If we want an array to be sized based on input from the user, then we cannot use static arrays.

Are JavaScript arrays static or dynamic?

JavaScript Arrays are dynamic in nature, which implies that their length can be changed at the time of execution (when necessary). The run-time system automatically allocates dynamic arrays' elements based on the utilized indexes.

What is meant by static array?

An array is simply a data structure for holding multiple values of some type. So, a static array is simply an array at the class level that can hold multiple of some data type. For example: In your TravelRoute class, you may have a set number of possible destinations in a route.


1 Answers

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

like image 93
T.J. Crowder Avatar answered Oct 03 '22 04:10

T.J. Crowder