【问题标题】:Cannot read property 'length' of undefined in for loop on 2d array无法读取二维数组的 for 循环中未定义的属性“长度”
【发布时间】:2018-07-07 21:26:09
【问题描述】:

下面的javascript代码

function hasSpecialColumn(arr) {
  for (let col = 0; col < arr[0].length; col++) {

      let sumOfOnes = 0;

      for (let row = 0; row < arr.length; arr++) {
          if (arr[row][col] === 1) {
              sumOfOnes++;
              if (sumOfOnes >= 2) {
                  return true;
              }
          }
      }

  }
  return false;
}

const arr = [[3,4],[5,6]];
console.log(hasSpecialColumn(arr));

我在使用 nodejs 时遇到以下错误。

 Users/khaymahd/workspace/iv/for-loop-undefined-error.js:3
      for (let col = 0; col < arr[0].length; col++) {
                                    ^

    TypeError: Cannot read property 'length' of undefined
    at hasSpecialColumn (/Users/khaymahd/workspace/iv/for-loop-undefined-error.js:3:37)
    at Object.<anonymous> (/Users/khaymahd/workspace/iv/for-loop-undefined-error.js:21:17)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)

也在 chrome 控制台中尝试过

VM183:3 Uncaught TypeError: Cannot read property 'length' of undefined
    at hasSpecialColumn (<anonymous>:3:38)
    at <anonymous>:21:17

这是一个奇怪的错误!但是,如果我设置 size = arr[0].length 并在 for 循环中使用它,它就可以工作。但我不明白为什么原始代码不起作用。

【问题讨论】:

  • 你在这一行覆盖了你的数组:for (let row = 0; row &lt; arr.length; arr++) 那应该是row++。当您执行此操作时,arr 变为 NaN,并且在循环的下一次迭代中,它会尝试访问未定义的 NaN[0]

标签: javascript node.js for-loop undefined


【解决方案1】:

因为它似乎认为 arr[0] 是未定义的,请尝试输入 console.log(arr);console.log(arr[0])。其中之一可能会返回 undefined,这会导致您当前的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-01
    相关资源
    最近更新 更多