如何为"未定义"分配一个值?



我试图为一个空数组的项分配一个值,但我无法管理。我使用了Array构造函数,并尝试使用.map()for ... of,但都不起作用。

let chrom = new Array(4);
const randomN = () => Math.floor(Math.random()*2);
for (g of chrom) {
g = randomN()
}

然而,这个解决方案在中起作用

let emptyArr = new Array(4);
const randomN = () => Math.floor(Math.random()*2);
for (i=0; i<chrom.length; i++) {
chrom[i] = randomN()
}

不知怎么的,似乎只指定索引就可以了。有人知道为什么会发生这种事吗?我应该读什么?我试着查看文档,但什么也看不到。

解释是,在第一个解决方案中,g将是一个局部变量(副本(,而不是对chrom数组中实际值的引用。

例如:

let nums = [1, 2, 3]
for (let num of nums) {
num = 1 // num in this case is a totally different variable
}
console.log(nums) // will still output [1, 2, 3]

这是一篇很好的文章,解释了Javascript中值与引用之间的区别。

使用for...of循环不起作用,因为g只是一个保存当前索引处数组元素值的变量;修改它不会修改数组。

Array#map跳过所有空槽,如Array(size)new Array(size)创建的槽。带有空槽的数组文字如下所示:[,]。您可以在映射之前fill数组,也可以使用排列语法。

chrom.fill().map(randomN);
//or
[...chrom].map(randomN);

基于索引的标准for循环使用数组的length,其中包括空槽并使用索引设置元素,因此它具有所需的效果。

相关内容

最新更新