最近我正在做一些功课,不得不在只有 javascript 的多级数组中找到 0,所以如果有人需要,我就把这段代码留在这里:)var myArray = [ [2, 0, 10, 100], [3, 4, 5, 0, 10, 0], [11, 12, 11, 0, 10, 12, 0, 15, 0, 10, 0] ]; // ugnjezdeni nizovi var counter = 0; console.log(myArray, myArray[0].length, myArray[1].length, myArray[2].length); var arrayLenght1 = myArray[0].length; var arrayLenght2 = myArray[1].length; var arrayLenght3 = myArray[2].length; console.log(arrayLenght1, arrayLenght2, arrayLenght3); for (var iterator = 0; iterator <= myArray[0].length; iterator++) { // console.log("this is the current value " + iterator); mkay if (myArray[0][iterator] == 0) { counter = counter + 1; console.log("this is the count after a row 1 is passed " + counter); } } for (var iterator = 0; iterator <= myArray[1].length; iterator++) { if (myArray[1][iterator] == 0) { counter = counter + 1; console.log("this is the count after a row 2 is passed " + counter); } } for (var iterator = 0; iterator <= myArray[2].length; iterator++) { if (myArray[2][iterator] == 0) { counter = counter + 1; console.log("this is the count after a row 3 is passed " + counter); } } console.log("this is the final count after all the rows have been checked for 0 = " + counter);实际结果是您在变量的指定行中获得 0 的数量。
1 回答

沧海一幻觉
TA贡献1824条经验 获得超5个赞
如果您只是想计算零的数量,则有更有效的方法可以做到这一点
var myArray = [
[2, 0, 10, 100],
[3, 4, 5, 0, 10, 0],
[11, 12, 11, 0, 10, 12, 0, 15, 0, 10, 0]
];
myArray.map((row, rowNumber) => console.log(`number of zeros in row ${rowNumber}:`, row.filter(element => element === 0).length))
如果你想在所有行中总共有零,你可以这样做
var myArray = [
[2, 0, 10, 100],
[3, 4, 5, 0, 10, 0],
[11, 12, 11, 0, 10, 12, 0, 15, 0, 10, 0]
];
const [row1, row2, row3] = myArray.map((row, rowNumber) => row.filter(element => element === 0).length)
console.log(row1);
console.log(row1+row2);
console.log(row1+row2+row3);
添加回答
举报
0/150
提交
取消