为什么我的代码不返回字符最多的单词?

我试图让 JS 获得最多字符的单词,但由于某种原因,我的代码总是返回“The”


我已经尝试了两种代码变体。


变体 1:


let sent = "The quick borwn fox jumped over the jazy dog";

let word = findWord(sent);


function findWord(sent){


  splitSent=sent.split(" ");


  let largest="";


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


    if(splitSent[i].length>largest){


        largest=splitSent[i];

    }


  }


return largest;

}


console.log(word)

变体 2:


let sent = "The quick borwn fox jumped over the jazy dog";

let word = findWord(sent);


function findWord(sent){


  splitSent=sent.split(" ");


  let largest="";


  for(split of splitSent){


    if(splitSent[i].length>largest){


        largest=splitSent[i];

    }


  }


return largest;


}


console.log(word)

控制台只打印第一个代码中的“The”和第二个代码中的“fox”


郎朗坤
浏览 120回答 1
1回答

噜噜哒

因为你需要检查largest.length不largest。let sent = "The quick borwn fox jumped over the jazy dog";&nbsp; &nbsp;&nbsp;let word = findWord(sent);&nbsp; &nbsp;&nbsp;function findWord(sent) {&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; splitSent = sent.split(" ");&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; let largest = "";&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; for (i = 0; i < splitSent.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; if (splitSent[i].length > largest.length) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; largest = splitSent[i];&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; }&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; return largest;&nbsp; &nbsp;&nbsp;}&nbsp; &nbsp;&nbsp;console.log(word);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript