Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

In JavaScript development, there are often scenarios where you need to create arrays of property length. This article summarizes several techniques for creating or populating arrays of arbitrary length that can improve your programming efficiency.

Direct fill method

Take the primitive approach of manually filling the array of the desired length.

const arr = [0.0.0];
Copy the code

The for loop push ()

Much the same as the first method, except that you use a for loop to create an array of a specific length

var len = 3;
var arr = [];
for (let i=0; i < len; i++) {
  arr.push(0);
}
Copy the code

Array constructor method

var len = 3;
var arr = new Array(len);
Copy the code

inArrayAfter the constructorfill()methods

var len = 3;
var arr = new Array(len).fill(0);
Copy the code

If you fill() an Array with an object, all elements reference the same instance (that is, the object is not cloned multiple times, array.from () does not have this problem) :

var len = 3;
var obj = {};
var arr = new Array(len).fill(obj);
Copy the code

So manipulating the array should be faster than creating it using the constructor. Creating an array is slow, however, because the engine may need to reallocate contiguous memory multiple times as the array grows.

useundefinedFill the array

Array.from({length: 3})       // [ undefined, undefined, undefined ]
Copy the code

The following works only for iterable values and has a similar effect to array.from () :

[...new Array(3)]             // [ undefined, undefined, undefined ]
Copy the code

useArray.from()mapping

If you provide a mapping function as its second argument, you can use array.from () to map.

Populate the array with values

Array.from({length: 3}, () = > 0)        // [0, 0, 0]
Copy the code

Create arrays with unique (non-shared) objects

Array.from({length: 3}, () = > ({}))     // [{}, {}, {}]
Copy the code

Creates an array with an ascending integer sequence

Array.from({length: 3}, (x, i) = > i)    // [0, 1, 2]
Copy the code

Create with an arbitrary range of integers

var start = 2, end = 5;
Array.from({ length: end - start }, (x, i) = > i + start)    // [2, 3, 4]
Copy the code

Another way to create an array of ascending integerskeys()

[...new Array(3).keys()]              // [0, 1, 2]
Copy the code