for loop behavior “TypeError: Cannot read property 'length' of undefined”

时光毁灭记忆、已成空白 提交于 2021-02-11 14:06:59

问题


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);
  }

Without equal sign it works.

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)

Complete code

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");

Thank you and happy new year.


回答1:


Because the index of an array is always length - 1.

You can say. Suppose you have the array of length 2

const ar = ["a", "b"]

and if you check the length of this array it will show 2 but the max index of this array is 1 only.

So when you loop through the length of the array then it goes up to index 2 and res[2] is undefined




回答2:


Basically the indices of an Array are zero based.

If you loop until the length, the last index is one over.

array = [1, 2, 3] // length === 3

If you loop until 3,

array[3]

you get undefined, or if the element should be an object, then you get the above mentioned error.




回答3:


Arrays are zero based in JavaScript.

For example: If you have 3 numbers in an array var arr = [10,20,30] then the indices of these numbers will be 0 1, 2 i.e. You can access 10 with arr[0], 20 with arr[1] and 30 with arr[2].

Note that length of this array will be 3. So when you iterate in your loop from 0 to length you go one index extra therefore you get undefined. Either go from 0 to <= res.length - 1 or 0 to < res in your loop.



来源:https://stackoverflow.com/questions/54052561/for-loop-behavior-typeerror-cannot-read-property-length-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!