Why `new Array(5).map((x,y)=>y*2)` didn't work?

新手上路,请多包涵

问题描述

I was trying to create an array which is [1,2,3,...,n], so I used code new Array(10).map((value,index)=>index+1), but I got [empty × 5];

Meanwhile, new Array(10).fill(1).map((value,index)=>index+1), why?

How did Array.prototype.map() work?

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)

// [empty × 10]
new Array(10).map((value,index)=>index+1)

// [1,2,...,10]
new Array(10).fill(1).map((value,index)=>index+1)

你期待的结果是什么?实际看到的错误信息又是什么?

Why?

How did Array.prototype.map() work?

阅读 2.6k
3 个回答

new Array() 创建的是一个稀疏数组,对于稀疏数组 map、filter、foreach 等方法并不会调用传入的第一个参数(函数)

It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value)

参考:https://developer.mozilla.org...

how about

Array.apply(null,Array(4)).map((x, y)=>y*2)

keep your code like a function

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏