简体   繁体   English

查找并返回javascript中最长的单词

[英]find & return the longest word in javascript

Can someone please let me know what is going wrong here? 有人可以让我知道这里出了什么问题吗? Whenever I type in this as a test case (console.log(longestWord("what the hell is going on")) and I get 'what' back as the longest word...it works on pretty much every other case I tested ...its driving me crazy please help. thank you!!! 每当我将其输入为测试用例时(console.log(longestWord(“到底发生了什么事”)),当最长的单词返回“ what”时,它几乎可以在我测试过的所有其他情况下使用...让我发疯,请帮忙,谢谢!!!

function longestWord(string) {
var words = string.split(' ');

for (var i = 0; i < words.length; i++) {
    var currentWord = words[i];

    var longestWord = words[0];

    if (longestWord.length < currentWord.length) {
         longestWord = currentWord;
    }
}
return longestWord;
}

You were resetting your longest word with every iteration of the loop. 您正在循环的每次迭代中重置最长的单词。 Set initial (first) longest word before the loop runs and then it will work properly. 在循环运行之前设置初始(第一个)最长的字,然后它将正常工作。

 function longestWord(string) { var words = string.split(' '); // Set the intial longest word out here var longestWord = words[0]; // Need to loop through from index 1 for (var i = 1; i < words.length; i++) { var currentWord = words[i]; // Setting the longest word to the initial word here means that it will set the longest word to be "what" everytime your loop runs. if (longestWord.length < currentWord.length) { longestWord = currentWord; } } return longestWord; } console.log(longestWord("What the hell is going on")); 

Jordan has given you the correct answer. 乔丹给您正确的答案。 We can also use sort function and return the first element as follows: 我们还可以使用sort函数并返回第一个元素,如下所示:

 function longestWord(string) { var words = string.split(' '); return words.sort(function (a, b) { return b.length - a.length; })[0]; } console.log(longestWord("what the hell is going on")) 

I post the ES6 one-liner, just in case... 我贴上ES6单线纸,以防万一...

 let longestWord = str => str.split(' ').sort((a, b) => b.length - a.length)[0]; console.log(longestWord("what the hell is going on")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM