关于JS数组的知识

版权声明:任先阳 任 先 阳 任先 先阳,nvcc.cc、www.nvcc.cc、sbfox.com、www.sbfox.com https://blog.csdn.net/qq_39571197/article/details/84578185

如何生成指定长度且值不为empty的数组?

1、推荐Array.from方法,而且它可以接收回调函数

Array.from({length:10});
// [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
Array.from({length:10},(v,index)=>index);// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

2、Array.apply(null,{length:n}),可以指定任意位置的值

const arr = Array.apply(null,{length:10});
arr;// [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
arr.forEach((v,index,array)=>array[index]= index);
arr;// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Array.apply(null,{1:'哈哈',3:false,5:10,6:55,length:10});
// [undefined, "哈哈", undefined, false, undefined, 10, 55, undefined, undefined, undefined]

 

 

阅读更多

没有更多推荐了,返回首页