gpt4 book ai didi

javascript - 无法读取二维数组的 for 循环中未定义的属性 'length'

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:34 24 4
gpt4 key购买 nike

对于下面的 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));

我在使用 Node.js 时遇到以下错误。

 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 循环中使用它,它就可以工作。但我不明白为什么原始代码不起作用。

最佳答案

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

关于javascript - 无法读取二维数组的 for 循环中未定义的属性 'length',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51227055/

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