Initializing an array in JavaScript


Hello.

When I create an array

var thingsv = new Array(length)

I don't have the option to initialize it with the initial values, because the call forms

var thingsv = new Array(length, value)

In the language there is no (I did not find it). We have to run through the array in a loop and fill it in. Isn't there a more convenient way?

Thanks.

Author: Nicolas Chabanovsky, 2010-12-22

2 answers

For example, this way you can initialize an array of 10 elements, each of which has the character *:

Array(10).join('*').split('')
 4
Author: vitkarpov, 2019-11-12 15:04:43

Preface


There is no new Array(length, value) construction in JS, due to the way the Array() constructor works. If it takes a single value as an argument, for example, length, and typeof length == 'number' (type casting will not work here, even .valueOf() will not be called for the object), then an empty array will be created, filled with something incomprehensible, from length elements.

You can even notice that in different browsers in the console it will look different, in general, it's so easy to leave this is not desirable. But when this condition is not met, an array is created, the elements of which will be everything that is specified in the arguments of the constructor.

By the way, the entry Array() and new Array() is no different. And to initialize an empty array, it is better (it is more pleasant for the browser) to write var mas = [], and not var mas = Array().

Act One


Unfortunately, the native filling of the entire array appeared only recently, with the arrival of ES6, and is still poorly supported browsers, but as a fact there is:

Array(1000).fill(-1);

This construction will fill the entire thousand array elements with the value -1. Plus, as a feature, in the function you can set from what to what value to fill in. A full description of the operation of this function and its polyfill can be found here.

Act Two


For fun, we can suggest another method that appeared in ES6. We will use the function Array.prototype.from(), it is also not very supported by browsers, but slightly better than Array.prototype.fill():

Array.from({length: 1000}, () => -1);
Array.from({length: 1000}, function() { return -1; }); // аналогично

It accepts two objects. Array-like object (something that has the length property), and second, a function to call on each element of the new array (in fact, an implicit .map() will be executed). A detailed description and polyfill can be found here.

Act Three


With the advent of ES5, it became possible to fill the array using the Array.prototype.map() function like this:

Array.apply(null, {length: 1000}).map(function() {return -1});

Or if you make a joke and add a pinch of ES6, then you can do it like this:

Array.apply(null, {length: 1000}).map(() => -1);

I think we need to chew a little. Array.prototype.map() will ignore all empty values of the newly created array (remember, I wrote that there is something incomprehensible there), so we need to make them explicit. We do it like this: Array.apply(null, {length: 1000}). As a context, it does not matter what to pass, but as an argument, we will pass the array-like object. To iterate by elements, only the length field is needed, and since there are no elements, the values will always be undefined. The method is working, but it is better not to write like this.

Act Four


You can do this the old-fashioned way by first doing Array.prototype.join(), joining all the elements into a string, and then Array.prototype.split(), dividing the array into atomic entities.

Array(1000).join('-1').split('');

Plus, it works everywhere. The disadvantage is that you can only fill the array with text values, as a result, you need to perform a cast to get numbers, and yet it is slow.

Act five, for justice


I think we should also write about the most proven and fastest method of filling arrays with data:

var array = [];
for (var i = 0; i < 1000; ++i) {
    array.push(-1);
}

Faster and more convenient implementation:

var array = Array(1000);
for (var i = 0; i < array.length; array[i++] = -1);

Conclusion


You should always choose the method of filling the array with data (as well as everything else) wisely, and I will just give a small comparative test of the speed of performing all operations on jsPerf. Be careful, some of the tests will not work on older browsers.

 3
Author: Rolandius, 2015-10-09 16:12:35