for循环行为"TypeError:无法读取未定义的属性'length'" [英] for loop behavior "TypeError: Cannot read property 'length' of undefined"
问题描述
对于已经问过的此类问题,我没有找到答案.我不明白,为什么当我的for循环包含此条件
I don't find an answer in the replies to this kind of question already been asked. I don't understand, why console throws this error "TypeError: Cannot read property 'length' of undefined" , when my for-Loop contains this condition
for (let i = 0; i <= res.length; i++) {
arr.push(res[i].length);
}
没有等号.
我不明白为什么.我以为设置i = 1会起作用.但事实并非如此.谁能解释,为什么在给出条件时出现错误
I don't get why. I thought setting i=1 would work. But it does not. Could anyone explain please, why I get the error when given the condition
i>**=**res.length; (with equal sign)
完整代码
function findLongestWordLength(str) {
var arr = [];
var res = str.split(" ");
for (let i = 1; i < res.length; i++) {
arr.push(res[i].length);
}
return Math.max(...arr);
}
findLongestWordLength("May the force be with you");
谢谢你,新年快乐.
推荐答案
因为数组的索引始终为长度-1.
您可以说.假设您的数组长度为2
You can say. Suppose you have the array of length 2
const ar = ["a","b"]
,如果您检查此数组的长度,它将显示 2 ,但此数组的最大索引仅为 1 .
and if you check the length of this array it will show 2 but the max index of this array is 1 only.
因此,当您遍历数组的长度时,它会上升到索引2,而 res [2]
是 undefined
So when you loop through the length of the array then it goes up to index 2 and res[2]
is undefined
这篇关于for循环行为"TypeError:无法读取未定义的属性'length'"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!