Find the longest word in a string using javascript

后端 未结 10 1180
长情又很酷
长情又很酷 2021-01-16 23:06

I\'m trying to find the longest word in a string, but it continually returns the length of the first word. Any ideas?

Here\'s my code:

function findL         


        
10条回答
  •  囚心锁ツ
    2021-01-16 23:53

    Your return statement is in the wrong place, as mccainz said, however you should also be saving the word if you want to return the actual word.

    function findLongestWord(str) {
      var words = str.split(' ');
      var longestLength = 0;
      var longestWord;
      for (var i=0;i longestLength) {
           longestLength = words[i].length;
           longestWord = words[i];
        }
      }
      return longestWord;
    }
    

提交回复
热议问题