头图

In the JavaScript , it is often necessary to create a feature length array. This article summarizes several tips for creating or filling arrays of arbitrary length, and learned how to improve programming efficiency.

Direct filling method

Using the most primitive method, manually fill the array of the required length.

const arr = [0,0,0];

for loop push() method

for first method, just use 0617b479b48c6b loop to create an array of a specific length

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

Array constructor method

var len = 3;
var arr = new Array(len);

Add the fill() method after the Array

var len = 3;
var arr = new Array(len).fill(0);
If you use an object as a parameter to fill() , all elements will refer to the same instance (that is, the object is not cloned multiple copies, Array.from() does not have this problem):
var len = 3;
var obj = {};
var arr = new Array(len).fill(obj);
So it should be faster to manipulate this array than to create it with the constructor. However, the speed of creating an array is slow, because the engine may need to reallocate contiguous memory multiple times as the array grows.

Fill the array with undefined

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

The following method is only suitable for iterable values, and has a similar effect to Array.from():

[...new Array(3)]             // [ undefined, undefined, undefined ]

Use Array.from() for mapping

If you provide a mapping function as its second parameter, you can use Array.from() for mapping.

Fill the array with values

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

Create an array using unique (non-shared) objects

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

Create an array with a sequence of ascending integers

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

Create with any range of integers

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

Another way to create an ascending integer array uses keys()

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

dragonir
1.8k 声望3.9k 粉丝

Accepted ✔