javascript foreach在一个矩阵



我有一个矩阵,由0、1和"x"组成。我尝试使用forEach()"方法,以便找到"x"。然后用另一个值替换它。我该怎么做呢?

let a=new Array
for(int i=0;i<=5;i++) {
a[i]=new Array
for(int j=0;j<=5;j++) {
a[i][j]=Math.round(Math.random())
}
}
a[3][2]="X" //the indexes are random values
for(int i=0;i<=5;i++) {
for(int j=0;i<=5;j++) {
if(a[i][j]=="X") {
a[i][j]="found"
break
}
}
}
let matrix1 = [
[0, 1, 0, 1, 1],
[1, 0, 1, 1, 1],
[0, 1, 1, 0, 0],
[1, 0, 1, 0, 1],
[0, 1, 1, 'x', 1]
];
matrix1
.forEach((element1, index1, array1) => { 
element1.forEach((element2, index2, array2) => {
if(array1[index1][index2] == 'x') {
array1[index1][index2] = 'y';
}
});
});

可能有其他(和更好的解决方案),但这应该可以工作。但是我建议使用两个嵌套for循环。
对于forEach方法,必须创建两个lambda函数,当它们被调用时,会发生上下文切换(不确定,可能会被javascript解释器优化/删除)。因此,内存占用可能会稍微高一些,而性能可能会降低。但是对于一个5x5矩阵,这些都不重要。
普通的for循环也更具可读性——至少对我来说;)

我将使用for-of循环而不是使用forEach。

let matrix = [
[0, 1, 0, "x", 1],
[1, 0, 1, 1, 1],
[0, "x", 1, 0, 0],
["x", 0, 1, 0, 1],
[0, 1, 1, 0, 1]
];
for (const [i, row] of matrix.entries()) {
for (const [j, element] of row.entries()) {
if (element === "x") {
matrix[i][j] = "Boom";
}
}
}

最终,输出将是:

[
[0, 1, 0, "Boom", 1],
[1, 0, 1, 1, 1],
[0, "Boom", 1, 0, 0],
["Boom", 0, 1, 0, 1],
[0, 1, 1, 0, 1]
]

最新更新