Efficient way to create and fill an array with consecutive numbers in range

徘徊边缘 提交于 2019-12-24 11:15:56

问题


for the moment i use this JavaScript to create an array with n numbers from 0 to n

// javascript populate array 
var n=1000;
var arr=[n];
for (i=n;i>=0;i--) {
arr[i]=i;
console.log(arr[i]);
} 

is it the fast/right way to do the task?


回答1:


You can do declarative approach while using Array.from like this:

arr = Array.from({length: 20}, (e, i)=> i)
console.log(arr)



回答2:


An ES6 way of doing it using Array.keys():

let n = 10;
let arr = Array.from(Array(n).keys());

console.log(arr);

Made a quick JSPerf with answer so far:

https://jsperf.com/array-filling-so/




回答3:


You can use the function map skipping the first param of the predicate and getting the index i.

let arr = Array(10).fill().map((_, i) => i);
console.log(arr);



回答4:


The shortest way (I think) [...Array(10)].map((a,b)=>b)

console.log(
  [...Array(10)].map((a,b)=>b)
)


来源:https://stackoverflow.com/questions/55579499/efficient-way-to-create-and-fill-an-array-with-consecutive-numbers-in-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!