我准备创建一个长度是1000的数组, 数组中是0 ~ 1000 的随机数, 开始我是这样写的
new Array(1000).map(() => parseInt(Math.random() * 1001));
结果得到的是1000个 empty
image.png
然后再网上找到了原因
new Array() 创建的是一个稀疏数组,对于稀疏数组 map、filter、foreach 等方法并不会调用传入的第一个参数
解决方法
new Array(1000).fill(undefined).map(() => parseInt(Math.random() * 1001));
or
Array.apply(null, Array(1000)).map(() => parseInt(Math.random() * 1001));
or
[...new Array(1000)].map(() => parseInt(Math.random() * 1001));
延伸
当我将new Array(1000)的第0位置成undefined则使用 map 函数 第0位生效
const list = new Array(1000);
list[0] = undefined;
list.map(() => parseInt(Math.random() * 1001));
image.png
随后我使用 splice 和 slice 函数截取 new Array(1000) , 截取后的数组还是无法使用 map 方法来创建随机数
new Array(1000).splice(0).map(() => parseInt(Math.random() * 1001));
new Array(1000).slice().map(() => parseInt(Math.random() * 1001));
image.png
因此 得出结论 如果数组的内容没有被定义, 还是empty的状态, 则不能调用map












网友评论