This is the fourth day of my participation in the August Text Challenge.More challenges in August

preface

I am working on a requirement these days. I need to generate a fixed length array. The elements of the array start from 0 and increase successively. Finally I generated it using a for loop. Is there another way to do it besides the for loop?

The answer is yes.

Here sum up these methods below, convenient back check leak fill a vacancy, consolidate these knowledge points at the same time.

In all of the examples below, I’ve used 10 instead of N, and you can change 10 to whatever number you want

The for loop

This should be the most conventional approach, and the easiest to think of.

Without further ado, let’s get straight to the code:

let arr = []
for(let i = 0; i < 10; i++) {
  arr.push(i)
}
console.log(arr) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

So what else are there besides the for loop?

Array.from

Array.from converts an Array or iterable into a real Array.

Array.from takes three arguments

  • obj

    Mandatory. An array of classes or iterable objects to be converted, such as node, Set,Map, etc

  • fn

    Optionally, the callback function is executed on each element of the converted array

  • thisArgs

    Optional. If the callback function needs to specify this, this can be supplied

Note that obj will generate an array of length whenever it has a length attribute

So here we can write:

Array.from({length: 10}, (val, i) = > i) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

In addition,

We can also use the keys method on the Array prototype chain, which returns an Iterator object with an Array index and passes that object to array. from

The following code

Array.from(new Array(10).keys()) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

We can also use object. keys, which gets the key property of an Object and returns an array.

If the object is an array, the key is the index of the array

So here we can write:

Object.keys(Array.from({length: 10})) / / / "0", "1", "2", "3", "4", "5", "6", "7", "eight" and "9"]
Copy the code

But the elements of the array are strings, so we can refine it a little bit

Object.keys(Array.from({length: 10})).map((val, i ) = > +i) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

Extended operator

An extension operator that expands objects that have an Iterator interface

So we can change the example above

Keys () returns objects from the Iterator interface

[...new Array(10).keys()]; // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

[...Array.from({length: 10}).keys()] // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Copy the code

conclusion

That’s my list of ways to quickly generate arrays from 1 to N, but it’s not limited to that. If there are other ways, feel free to comment.

The most common of these methods is the for loop, but you can also learn about array. form and extension operators, and it’s always a good idea to learn more about them.

I hope it was helpful.