How to Initialize an Array's Length in JavaScript

How to initialize an array's length in JavaScript?

  1. Why do you want to initialize the length? Theoretically there is no need for this. It can even result in confusing behavior, because all tests that use the length to find out whether an array is empty or not will report that the array is not empty.

    Some tests show that setting the initial length of large arrays can be more efficient if the array is filled afterwards, but the performance gain (if any) seem to differ from browser to browser.

  2. jsLint does not like new Array() because the constructer is ambiguous.

    new Array(4);

    creates an empty array of length 4. But

    new Array('4');

    creates an array containing the value '4'.

Regarding your comment: In JS you don't need to initialize the length of the array. It grows dynamically. You can just store the length in some variable, e.g.

var data = [];
var length = 5; // user defined length

for(var i = 0; i < length; i++) {
data.push(createSomeObject());
}

How to create an array containing 1...N

If I get what you are after, you want an array of numbers 1..n that you can later loop through.

If this is all you need, can you do this instead?

var foo = new Array(45); // create an empty array with length 45

then when you want to use it... (un-optimized, just for example)

for(var i = 0; i < foo.length; i++){
document.write('Item: ' + (i + 1) + ' of ' + foo.length + '<br/>');
}

e.g. if you don't need to store anything in the array, you just need a container of the right length that you can iterate over... this might be easier.

See it in action here: http://jsfiddle.net/3kcvm/

javascript create empty array of a given size

var arr = new Array(5);
console.log(arr.length) // 5

Create array with length n, initialize all values with 0 besides one which index matches a certain condition, in O(1)?

You need to assign n values, and so there is that amount of work to do. The work increases linearly with increasing n.

Having said that, you can hope to make your code a bit faster by making use of .fill:

const data: number[] = Array(n).fill(0);
data[someIndex] = someNumber;

But don't be mistaken; this is still O(n): .fill may be faster, but it still requires to fill the whole array with zeroes, which means a corresponding size of memory needs to be initialised, so that operation has linear time complexity.

If however you drop the requirement that zeroes need to be assigned, then you can only store the someNumber:

const data: number[] = Array(n);
data[someIndex] = someNumber;

This way you actually do not allocate the memory for the whole array, so this code snippet runs in constant time. Any access to an index different from someIndex will give you a value of undefined. You may trap that condition and translate that to a zero on-the-fly:

let value = i in data ? data[i] : 0;

Obviously, if you are going to access all indices of the array like that, you'll have again a linear time complexity.

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

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

How to declare a Fixed length Array in TypeScript

The JavaScript array has a constructor that accepts the length of the array:

let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]

However, this is just the initial size, there's no restriction on changing that:

arr.push(5);
console.log(arr); // [undefined × 3, 5]

TypeScript has tuple types which let you define an array with a specific length and types:

let arr: [number, number, number];

arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'

Javascript - Initialize array with nulls

With EcmaScript 6 (ES2105), creating an array containing five nulls is as easy as this:

const arr = new Array(5).fill(null);

MDN Reference



Related Topics



Leave a reply



Submit