[removed] find longest word in a string

前端 未结 30 2672
余生分开走
余生分开走 2020-11-27 03:50
function longestWord(string) {
    var str = string.split(\" \");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length - 1; i++) {
                


        
30条回答
  •  庸人自扰
    2020-11-27 04:11

    The index is going up to str.length -1:

    for (var i = 0; i < str.length - 1; i++) {
    

    So the last word is not processed.

    Try with: longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice"). You'll see it works (returns AAAAAAAAAAAAAAAAAAAAAAAAA).

    In case you're in doubt, the simplest way to fix it is removing the -1 from the for loop.

    for (var i = 0; i < str.length; i++) {
    

    Check a demo with both versions (the problematic and the fixed): link here.

提交回复
热议问题