Js不使用循环生成长度为10内容分别为0-9的数组的方法?六种

1、使用Array.apply

let arr= Array.apply(null, { length: 10 }).map((item,index)=>{
     return index;
    });
console.log(arr);
//(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
复制代码

原理:Array.apply的第二个参数是类数组调用Array.apply(null, { length: 10 })等于生成了长度为10内容都为undefinded的数组数组

2、使用Array.from

let arr= Array.from({length:10}).map((item,index)=>{
     return index;
    });
  console.log(arr);
//(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
复制代码

3、使用Array.prototype.fill

let arr=  new Array(10).fill(1).map((item,index)=>{
     return index;
    });
   console.log(arr);
//(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
复制代码

说明一下:new Array(10).fill(1)生成一个长度为10的空数组并用1填充bash

4、使用setInterval

var arr = [],
    i = 0,
    timer = null;
    timer = setInterval(() => {
    i < 10 ? arr.push(i++) : clearInterval(timer);
        }, 0);
    console.log(arr);
复制代码

其实用setTimeout里面嵌套setTimeout也能够实现,有兴趣的能够试一下app

5、使用split+join

var arr=new Array(10).join(',').split(',').map((item,index)=>{
           return index;
       })
        console.log(arr);
复制代码

这里为啥要用join(',').split(',')搞一把,new Array(10)生成的每一项都为空,map循环的时候会跳过空项ui

6、递归

var arr=[];
function makeArr(count,arr){
 count--;
 arr.unshift(count);
 if(count==0){
     return;
 }else{
    makeArr(count,arr);  
 }
}
makeArr(10,arr);
console.log(arr);
复制代码
相关文章
相关标签/搜索