Find the longest word in a string using javascript

后端 未结 10 1183
长情又很酷
长情又很酷 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:40

    Your return statement is misplaced, put it after the loop :

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

提交回复
热议问题