找到&返回javascript中最长的单词

时间:2017-05-18 22:00:26

标签: javascript

有人可以告诉我这里出了什么问题吗?每当我输入这个作为一个测试用例(console.log(longestWord(“到底是怎么回事”))并且我得到'什么'作为最长的单词...它几乎适用于我测试的每一个其他情况...它让我疯狂请帮助。谢谢!!!

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;
}

3 个答案:

答案 0 :(得分:1)

您在循环的每次迭代中重置了最长的单词。在循环运行之前设置初始(第一个)最长的单词,然后它将正常工作。

&#13;
&#13;
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"));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

乔丹给了你正确的答案。我们也可以使用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"))

答案 2 :(得分:0)

我发布了ES6单行,以防万一...

let longestWord = str => str.split(' ').sort((a, b) => b.length - a.length)[0];

console.log(longestWord("what the hell is going on"));