2D数组赋值中意外的“未定义”元素

时间:2017-09-11 17:00:06

标签: javascript multidimensional-array ecmascript-6 nested-loops

以下是我的完整代码。由于某种原因,在设置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;
    }
}

1 个答案:

答案 0 :(得分:1)

它失败了,因为你错误地创建了你的电路板。它在2处失败,因为你有[[],[]]。如果你有[[]]那么它会在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;
    }
}