I can't use .map
on an array created by the Array-constructor with a set length:
我不能在具有设定长度的Array-constructor创建的数组上使用.map:
// create an array with 9 empty elements
let array = new Array(9);
// assign an array to each of the array's elements
array = array.map(() => new Array(1, 2, 3));
console.log(array);
One way to achieve the desired effect by using a for loop:
通过使用for循环实现所需效果的一种方法:
// create an array with 9 empty elements
let array = new Array();
// assign an array to each of them
for(let i = 0; i < 9; i++){
array.push(new Array(1, 2, 3));
}
console.log(array)
Why can't .map
be used on an array with empty
placeholders? What is the purpose of the Array(3)
- syntax?
为什么.map不能用于具有空占位符的数组? Array(3)的目的是什么 - 语法?
1 个解决方案
#1
3
You can use new Array(n)
to create a sparse array, an array with gaps, with the length of n
. According to MDN article about Array#map:
您可以使用新的Array(n)创建一个稀疏数组,一个带有间隙的数组,长度为n。根据MDN关于Array#map的文章:
Due to the algorithm defined in the specification if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.
由于规范中定义的算法,如果调用的映射数组是稀疏的,则生成的数组也将是稀疏的,保持相同的索引为空。
To solve that, you can use Array#fill, to fill the sparse array with a value (even undefined
will do), and then you can map it with whatever you want.
要解决这个问题,你可以使用Array#fill,用一个值填充稀疏数组(甚至是未定义的),然后你可以用你想要的任何颜色映射它。
// create an array with 9 empty elements
const array = new Array(9);
// assign an array to each of the array's elements
const result = array
.fill()
.map(() => [1, 2, 3]);
console.log(result);
#1
3
You can use new Array(n)
to create a sparse array, an array with gaps, with the length of n
. According to MDN article about Array#map:
您可以使用新的Array(n)创建一个稀疏数组,一个带有间隙的数组,长度为n。根据MDN关于Array#map的文章:
Due to the algorithm defined in the specification if the array which map was called upon is sparse, resulting array will also be sparse keeping same indices blank.
由于规范中定义的算法,如果调用的映射数组是稀疏的,则生成的数组也将是稀疏的,保持相同的索引为空。
To solve that, you can use Array#fill, to fill the sparse array with a value (even undefined
will do), and then you can map it with whatever you want.
要解决这个问题,你可以使用Array#fill,用一个值填充稀疏数组(甚至是未定义的),然后你可以用你想要的任何颜色映射它。
// create an array with 9 empty elements
const array = new Array(9);
// assign an array to each of the array's elements
const result = array
.fill()
.map(() => [1, 2, 3]);
console.log(result);