问题
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