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

I am learning Ruby and JavaScript. Sometimes I need 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 (e.g. built-in) way to initialize this array than (0..9).to_a? Anyway, it's pretty fast.

But in JavaScript, I don’t know a single equally fast way to create it. I could iterate over the loop for, but I believe there should be a faster way. But what is it?

+4
source share
1 answer

You can use spread syntaxin combination with the method keys().

console.log([ ...Array(10).keys() ]);
Run codeHide result

Another way is to use the method Array.from.

console.log(Array.from({length: 10}, (_, k) => k)); 
Run codeHide result
+5

Source: https://habr.com/ru/post/1689167/


All Articles