对于以下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循环中使用它,它将起作用。但是我不明白为什么原始代码不起作用。
答案 0 :(得分:0)
由于似乎认为arr [0]未定义,请尝试放入console.log(arr);
和console.log(arr[0])
。其中之一可能会返回undefined,这会导致您当前的错误。