我有一个指定长度的数组,我试图用依赖于每个索引的值填充它。
let arr = new Array(someLength)
arr.map((v, i) => i * 2)
据我所知,这是行不通的,因为
map
跳过未定义的值。我有几个问题:
map
从事类似 [undefined, undefined]
的工作? 我知道我可以使用标准
for
循环,但想知道是否有更好的方法来做到这一点。for (let i = 0; i < arr.length; i++) {
arr[i] = i * 2
}
到目前为止,我已经找到了一种方法,但它并不是很干净。
arr = arr.fill(undefined).map((foo, i) => i * 2)
最佳答案
- Why does
.map
work on something like[undefined, undefined]
?
考虑这两种情况
let a1 = [];
a1.length = 2;
a1; // [undefined × 2]
// vs
let a2 = [undefined, undefined];
a2; // [undefined, undefined]
Object.keys
的结果是什么?在这些中的每一个上?Object.keys(a1); // []
Object.keys(a2); // ["0", "1"]
所以,我们可以看到两者之间的区别——一个有初始化的键,另一个没有
- Is there anyway to accomplish this using ES6 array methods?
您已经指出
.fill
, 你也可以使用 Array.from
Array.from({length: 5}, (itm, idx) => 2 * idx); // [0, 2, 4, 6, 8]
关于javascript - 使用空元素迭代 Array (ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162398/