[英]TypeError: cannot read property 'length' of undefined (defined by function parameter)
I'm trying to make the simple code below works, but always got the following error: TypeError: cannot read property 'length' of undefined . 我试图使下面的简单代码有效,但始终出现以下错误: TypeError:无法读取undefined的属性“ length” 。
function multiplyAll(arr) {
var product = 1;
if (arr === undefined) {
return "Undefined Array!";
} else {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; i++) {
product *= arr[i][j];
}
}
return product;
}
}
multiplyAll([[7,2],[6,4],[5,8,9]]);
What is the problem? 问题是什么?
This appears to be a copy&paste/typo error: 这似乎是复制和粘贴/错字错误:
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr[i].length; i++)
In the inner for loop, you're incrementing i
instead of j
. 在内部for循环中,您将递增i
而不是j
。 You're going off the end of the array, making arr[i]
undefined. 您将离开数组的末尾,使arr[i]
未定义。
You could have solved this by monitoring the values of i
and j
using a debugger or calls to console.log
. 您可以通过使用调试器或调用console.log
监视i
和j
的值来解决此问题。 You would have noticed that i
was incrementing too fast, while j
remained at 0. 您可能已经注意到, i
增长速度太快了,而j
保持为0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.