二维数组赋值中出现意外的 "undefined" 元素

Unexpected "undefined" element in 2D array assignment

下面是我的完整代码。出于某种原因,它在设置 board[2][0] 时失败了,我不明白为什么。我敢肯定这很简单...

function randColor() {
    min = Math.ceil(0);
    max = colors.length;
    return colors[Math.floor(Math.random() * (max - min)) + min]; 
}

const colCount = 10;
const rowCount = 10;

var board = [[],[]];

const colors = ["#f00","#0f0","00f"];

class piece {
    constructor(value, color) {
        this.value = value;
        this.color = color;
    }
}

for (var x = 0; x < colCount; x++) {
    for (var y = 0; y < rowCount; y++) {
        var p = new piece('b',randColor());
        console.log("Setting board[" + x + "][" + y + "]");
        board[x][y] = p;
    }
}

它失败了,因为你创建的面板不正确。它在 2 处失败,因为您有 [[ ],[ ]]。如果你有 [[ ]]..等等 3 等等,它会在 1 处失败。

另外,您的行是您的外循环,列是您的内循环。以下将满足您的需求。

function randColor() {
    min = Math.ceil(0);
    max = colors.length;
    return colors[Math.floor(Math.random() * (max - min)) + min]; 
}

const colCount = 10;
const rowCount = 10;

var board = [];

const colors = ["#f00","#0f0","00f"];

function piece(value, color) {
    this.value = value;
    this.color = color;
}

for (var x = 0; x < rowCount; x++) {
    board[x] = [];
    for (var y = 0; y < colCount; y++) {
        var p = piece('b', randColor());
        console.log("Setting board[" + x + "][" + y + "]");
        board[x][y] = p;
    }
}