【问题标题】:JavaScript Reading Array - Cannot read property '0' of undefinedJavaScript 读取数组 - 无法读取未定义的属性“0”
【发布时间】:2018-03-14 23:14:12
【问题描述】:

当我运行下面的代码时,浏览器控制台中出现错误 内容为:未捕获的类型错误:无法读取未定义的属性“0”

尽管我对错误的性质感到好奇,但代码确实打印了我的意图。 我已将输出粘贴在这篇文章的底部。

var chessBoard = [];
for(let i = 0; i < 8; i++) {
   chessBoard[i] = [];
   for(let j = 0; j < 8; j++) {
   chessBoard[i][j] = (i + j)% 2 === 0 ? 'Black' : 'White';
}} // populate a 2 dimensional array with colors representing a chess board.

for(let i = 7; i => 0; i--) {
    let str_horizontal = '';
    for (let j = 0; j < 8; j++) {
        str_horizontal += chessBoard[i][j];
    }
    console.log(str_horizontal);
}

白黑白黑白黑白黑 VM116:13 黑白黑白黑白黑白 VM116:13 白黑白黑白黑白黑 VM116:13 黑白黑白黑白黑白 VM116:13 白黑白黑白黑白黑 VM116:13 黑白黑白黑白黑白 VM116:13 白黑白黑白黑白黑 VM116:13 黑白黑白黑白黑白 VM116:11

未捕获的类型错误:无法读取未定义的属性“0” 在:11:40

我已经为此苦苦挣扎了一段时间,但进展甚微。 我看不到问题所在。感谢您的帮助,谢谢。

【问题讨论】:

  • =&gt; 不是你想的那样,写操作符时要多加小心。
  • 用艾伦·帕特里奇的话...啊哈哈哈哈!!
  • 非常感谢

标签: javascript arrays undefined


【解决方案1】:

在您的 for 循环中,您使用的是箭头函数,而不是 =&gt; put &gt;=

var chessBoard = [];
for(let i = 0; i < 8; i++) {
   chessBoard[i] = [];
   for(let j = 0; j < 8; j++) {
   chessBoard[i][j] = (i + j)% 2 === 0 ? 'Black' : 'White';
}} // populate a 2 dimensional array with colors representing a chess board.

for(let i = 7; i >= 0; i--) {
    let str_horizontal = '';
    for (let j = 0; j < 8; j++) {
        str_horizontal += chessBoard[i][j];
    }
    console.log(str_horizontal);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多