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