问题
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