javascript代码以检查多级数组中的特定数字

时间:2019-05-16 17:20:26

标签: javascript arrays

最近您好,我正在做一些作业,不得不在只有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 个答案:

答案 0 :(得分:1)

如果您只是想计算零的数量,那么有更有效的方法

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);