我有一个指定长度的数组,我想要填充它的值取决于每个索引。
let arr = new Array(someLength)
arr.map((v, i) => i * 2)
据我所知,这不起作用是因为map
跳过未定义的值。
我有几个问题:
- Why does
map
work on something like[undefined, undefined]
? Is there anyway to accomplish this using ES6 array methods?
I know I can use a standard
for
loop, but was wondering if there's a nicer way to do it.for (let i = 0; i < arr.length; i++) { arr[i] = i * 2 }
I've found one method so far, it's not really clean though.
arr = arr.fill(undefined).map((foo, i) => i * 2)
.map()
不会跳过未定义的值;它会跳过未定义的属性/成员。 - user1106925[...Array(someLength)].map((_, i) => i * 2)
是另一种可能性。 - user1106925