JS Cannot read property “length” of undefined [closed]

我与影子孤独终老i 提交于 2019-12-25 18:53:17

问题


I'm trying to create an object using a given string where each word has a property stating its length.

var strings = {};

function findLongestWord(str) {
  var splitStr = str.split(" ");
    for (var i = 0; i <= str.length; i++){
     strings[splitStr[i]] = splitStr[i].length;
  }

  return strings;
}

findLongestWord("The quick brown fox jumped over the lazy dog");

I end up getting:

"TypeError": Cannot read property "length" of undefined.

If I were to replace splitStr[i].length with splitStr[0].length, the code runs properly, but of course giving me the same number for each word in the object.

Any help is appreciated, thanks.


回答1:


you are looping over wrong array. you should use i < splitStr.length.

  var strings = {};    
  function findLongestWord(str) {
  var splitStr = str.split(" ");
    for (var i = 0; i < splitStr.length; i++){
     strings[splitStr[i]] = splitStr[i].length;
  }

  return strings;
}


来源:https://stackoverflow.com/questions/44916065/js-cannot-read-property-length-of-undefined

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