Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

javascript - 'Length' Property Undefined while iterating Array

Iterating an array to find the longest string. Each time I've received the error Cannot read property length of undefined. Console.log tells me that the length of the array as well as the length of the string are being read and understood so I cannot understand where there is an undefined property. In fact, I've just about tripled the original length of the program trying to make sure every variable is defined but still no good. Any help would be greatly appreciated.

function findLongestWord(str) {
  var longest = 0;
  var array = str.split(" ");
  var arrayL = array.length;
  for (i=0; i<=arrayL; i++) {
    var currentWord = array[i];
    var currentL = currentWord.length;
    if (currentL > longest) {
      currentL = longest;
    };
  };
  return longest;
};

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

Edit: While the below answers did solve the issue, I also just wanted to mention for people that may later google this thread that I also had to swap my final if statement from currentL = longest; to longest = currentL since longest is what I was ultimately returning.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is the bounds of your iteration

for (i=0; i<=arrayL; i++) {

Note that you are going to be looking for array[array.length] doing this and that will always be undefined because the 10th item in an array of 10 items is [9], [10] is undefined.

Also, please use var here

for (var i=0; i < arrayL; i++) {

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...