寻找最长的单词而不是字符数时返回单词

时间:2014-11-03 19:54:02

标签: javascript string for-loop

所以,我正在研究一个查找字符串中最长单词的函数。但是,我无法找到如何控制.log实际的单词,而不是它拥有的字符数的值。这是我的功能:

function longestWord(text) {
var textSplit = text.split(" ");
for (var i = 0; i < textSplit.length; i++) {
    var wordLength = textSplit[i].length;
};
console.log(Math.max(wordLength));
}
longestWord("I dislike taking recent microwaves");

2 个答案:

答案 0 :(得分:1)

您可以使用减速器:

var longestWord = function(str) {
  return str.split(' ').reduce(function(acc, x) {
    return x.length > acc.length ? x : acc
  },'')
}

longestWord("I dislike taking recent microwaves"); //=> microwaves

答案 1 :(得分:1)

每当您检测到当前的长度超过最长的那个时,请保存它。

function longestWord(text) {
        var longestWordLength = 0;
        var longestWordString = '';

        var textSplit = text.split(" ");

        for (var i = 0; i < textSplit.length; i++) {
            var word = textSplit[i];
            var wordLength = word.length 
            if (longestWordLength < wordLength) {
                longestWordLength = wordLength;
                longestWordString = word;
            }
        };
        console.log(longestWordString);
    }
    longestWord("I dislike taking recent microwaves");

这是JS Fiddle