When I want to quickly generate 0-9 numbers with JS, the simplest way TO do this is new Array(10).

The print result is (10) [empty × 10], and an array of 10 is created, so the next step is written intelligently.

[0,1,2,3,4...] The new array
new Array(10).map((v,i) = > i);
// Print the result (10) [empty × 10], which is not the answer I wantCopy the code

The output is still an empty array of (10) [empty × 10], obviously unchanged, and I wonder if I can try forEach again.

var _numbers = [];
new Array(10).forEach((v,i) = > _numbers.push(i));
// Print the result []Copy the code

The output result is an empty array, not a single number is entered, it seems that map method is not the problem, began to think about solutions.

Plan 1:

Fill with fill()

A map generated with new Array(10) will not be called because the map callback will only be called on indexes that have values (including undefined). Indexes that have never been assigned a value or deleted with delete are not called. To be called by a map, each item in the array must have a value. Fill () is a method that fills all elements of an array with a fixed value.

new Array(10).fill().map((v,i) = > i);
// Print the result [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and the result is what I wantCopy the code

Scheme 2:

Use keys() to get the index value

[...new Array(10).keys()];
// Prints the result [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], which is also what I wantCopy the code

Using the keys() method makes the code much cleaner, and these two solutions can quickly address this requirement.

You ask, is that what new Array() is for? Isn’t the presence a little low?

More than that, of course, the new Array is only one parameter, will create a length of the first parameter value is an empty Array, when passing multiple arguments, will return to an Array parameter in sequence, to fill in the Numbers, for example, assume that you also need to fill in some Numbers into an Array by the regulation, such as I need to get a month month of 31 days, you can use like this:

new Array(1.3.5.7.8.10.12);
// Print the result [1, 3, 5, 7, 8, 10, 12]Copy the code

For example, if the number of arguments passed is not fixed, the new Array will create an empty Array of specified length, and the result will be completely different. In this case, we can use array.of () to solve this problem.

new Array(10.20.30) / / [10, 20, 30]
new Array(10) // (10) [empty × 10]
new Array(- 1) // Uncaught RangeError: Invalid array length

Array.of(10.20.30) / / [10, 20, 30]
Array.of(10) / / [10]
Array.of(- 1) // [-1]Copy the code

Avoid craters. If you have a requirement to initialize a large Array, use array.of () or the shorthand [] method.