由数组数组表示的表;不起作用

Table represented by array of arrays doesn't work

本文关键字:数组 不起作用 表示      更新时间:2024-04-24

我正在尝试创建一个数组数组,它将表示一个数字表。出于某种原因,第一行正在复制第二行。这是我的代码:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8],
    rows = 2,
    cols = 4,
    i,
    j,
    row = [],
    table = [];
for (i = 0; i < rows; i += 1) {
    for (j = 0; j < cols; j += 1) {
        row[j] = numbers[i * cols + j];
        console.log(row[j]);
        console.log(row);
    }
    console.log(row);
    table[i] = row;
}
console.log(table);

正如您所看到的,即使在第一行(i===0),写出当前数字也是正确的(1、2、3或4),但写出整行就是从第二行(5或5、6或5、7或5、5、6、7、8)写出数字。我是不是错过了一些显而易见的东西?谢谢

您只声明了var row=[]个。

因此,您继续向同一个变量写入,这将继续覆盖以前的值。

在循环中声明它,以保持重新设置。

var numbers = [1, 2, 3, 4, 5, 6, 7, 8],
    rows = 2,
    cols = 4,
    i,
    j,
    //row = [], not here - move to loop
    table = [];
for (i = 0; i < rows; i += 1) {
    var row = []; // declare row each time!
    for (j = 0; j < cols; j += 1) {
        row[j] = numbers[i * cols + j];
    }
    table[i] = row;
}

演示-每次时重新设置行


您总是引用相同的行数组,每次迭代都需要一个新的:

var numbers = [1, 2, 3, 4, 5, 6, 7, 8],
    rows = 2,
    cols = 4,
    i,
    j,
    table = [];
for (i = 0; i < rows; i += 1) {
    table[i] = [];
    for (j = 0; j < cols; j += 1) {
        table[i][j] = numbers[i * cols + j];
    }
}
console.log(table);