如何使用嵌套的For循环在新行上的数组中打印数组值?

时间:2013-08-23 11:55:01

标签: javascript arrays for-loop nested-loops

我正在尝试从阵列中的这些数组中获取数字以在新行上打印,但无法弄清楚如何引用它们以便将它们打印到控制台。我在这里缺少什么?

var numbers = [
    [1,2,3,4,5,6,7],
    [8,9,10,11,12,13,14,15,16],
    [17,18,19],
    [20],
    [21,22,23,24,25,26],
    [27,28,29,30]
];

for (i=0; i<numbers.length; i++) {
    for (j=0; j<numbers[i].length; j++) {
        console.log(numbers[i].j); //The problem is with this j here I suspect...
    }
}

4 个答案:

答案 0 :(得分:0)

尝试

for (i=0; i<numbers.length; i++) {
    for (j=0; j<numbers[i].length; j++) {
        console.log(numbers[i][j]); //The problem is with this j here I suspect...
    }
}

答案 1 :(得分:0)

numbers [i] .j以数字为每个数组访问属性j,你想要数字[i] [j]访问数组中的元素j [i]

答案 2 :(得分:0)

它应该以这种方式阅读:

var numbers = [
    [1,2,3,4,5,6,7],
    [8,9,10,11,12,13,14,15,16],
    [17,18,19],
    [20],
    [21,22,23,24,25,26],
    [27,28,29,30]
];

for (i=0; i<numbers.length; i++) {
    for (j=0; j<numbers[i].length; j++) {
        console.log(numbers[i][j]);
    }

}

答案 3 :(得分:0)

更改此

console.log(numbers[i][j]);