0%

Javascript 快速生成数组的方法

循环赋值

1
2
3
4
5
var arr1 = new Array(100);
for(var i=0;i<arr1.length;i++){
arr1[i] = i;
}
console.log(arr1);

push方法实现

1
2
3
4
5
var arr2 = new Array();
for(var i=0;i<100;i++){
arr2.push(i);
}
console.log(arr2);

while

1
2
3
4
5
6
7
var arr3 = new Array();
var i = 0;
while(i<100){
arr3.push(i);
i++;
}
console.log(arr3);

do while

1
2
3
4
5
6
7
8
var arr4 = new Array();
var i = 0;
do{
arr4.push(i);
i++;
}
while(i<100)
console.log(arr4);

Object.keys

1
2
3
4
5
6
var arr5 = Object.keys(Array.apply(null, {length:100})).map(function(item){

return +item;

});
console.log(arr5);

Array.from

1
2
var arr6 = Array.from({length:100}, (v,k) => k);
console.log(arr6);
1
2
var arr7 = Array.from(Array(100), (v,k) =>k);
console.log(arr7);

new Array(100).keys()

1
2
var arr8 = new Array(100).keys();
console.log(Array.from(arr8));

递归

1
2
3
4
5
6
7
8
9
10
var arr = [];
var i = 0;
function MakeArray(num){
if(i<num){
arr[i] = i++;
MakeArray(num);
}
return arr;
}
console.log(MakeArray(100));

new Array(100).toString()

1
2
3
4
var arr11 = new Array(100).toString().split(‘,‘).map(function(item,index){
return index;
});
console.log(arr11);

参考链接

https://www.cnblogs.com/fuzitu/p/10723869.html