gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:29:28 26 4
gpt4 key购买 nike

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

关于javascript - 二维数组赋值中出现意外的 "undefined"元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46160819/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com