11种JavaScript生成1到100的数组的方式
循环赋值
var arr = new Array(100);
for(var i=0;i<arr1.length;i++){
arr1[i] = i;
}
push方法实现
var arr = new Array();
for(var i=0;i<100;i++){
arr.push(i);
}
while
var arr = new Array();
var i = 0;
while(i<100){
arr.push(i);
i++;
}
do while
var arr = new Array();
var i = 0;
do{
arr.push(i);
i++;
}
while(i<100)
Object.keys
var arr = Object.keys(Array.apply(null, {length:100})).map(function(item){
return +item;
});
Array.from
var arr = Array.from({length:100}, (v,k) => k);
Array.from
var arr = Array.from(Array(100), (v,k) =>k);
new Array
var arr = new Array(100).keys();
setInterval
var arr = [];
var i = 0;
var timer = setInterval(function(){
arr[i] = ++i;
if(i>=100){
clearInterval(timer);
}
},1);
递归
var arr = [];
var i = 0;
function MakeArray(num){
if(i<num){
arr[i] = i++;
MakeArray(num);
}
return arr;
}
map
var arr = new Array(100).toString().split(',').map(function(item,index){
return index;
});