How to initialize an array of the first ten integers briefly?

Viewed 230

I'm studying Ruby and JavaScript. Occasionally I want an array of the first ten integers (or some other predictable series):

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In Ruby, is there a faster (like, built in) way to initialize this array than (0..9).to_a? Anyway, that's pretty fast.

But in JavaScript, I don't know of any similarly fast way to build it. I could iterate over a for loop but I figure there has to be a faster way. But what is it?

1 Answers

You can use spread syntax in combination with keys() method.

console.log([ ...Array(10).keys() ]);

Another way is to use Array.from method.

console.log(Array.from({length: 10}, (_, k) => k)); 

Related