gpt4 book ai didi

javascript - 矩阵所有行的值变化

转载 作者:行者123 更新时间:2023-11-30 20:31:17 24 4
gpt4 key购买 nike

所以我决定检查 Array.prototype.fill() 方法,因此我创建了一个简单的函数,它应该返回一个填充了空值或用户选择值的矩阵。

我的代码如下所示:

function Matrix(x,y,value){
if(value === undefined){
value = null;
}

let arr = new Array(y);
arr.fill(row());
return arr;

function row(){
let subarr = new Array(x);
subarr.fill(value);
return subarr;
}
}

乍一看效果很好。当我尝试重新分配其中一个值时出现问题。

let arr = Matrix(5,5);

arr[2][2] = 'marked as duplicate';
console.log(arr);

当然,我只希望其中一个值发生变化,但我得到的输出是这样的:

[ [ null, null, 'marked as duplicate', null, null, null, null ],
[ null, null, 'marked as duplicate', null, null, null, null ],
[ null, null, 'marked as duplicate', null, null, null, null ],
[ null, null, 'marked as duplicate', null, null, null, null ],
[ null, null, 'marked as duplicate', null, null, null, null ] ]

有人可以向我解释为什么会发生这种情况吗?

谢谢。

最佳答案

来自 MDN 对 Array.prototype.fill() 的描述(强调我的):

The fill() method fills all the elements of an array from a start index to an end index with a static value.

在这一行中:

arr.fill(row());

Array.fill() 不会为每个元素调用一次 row() 方法;它将调用它一次,并将该结果分配给数组的每个元素。

关于javascript - 矩阵所有行的值变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50310615/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com