14
function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length - 1; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    return word;
}

当我打电话时longestWord("Pride and Prejudice"),它返回'Pride'而不是'Prejudice',这是最长的单词......为什么?我检查了其他一些类似的问题,但解决方案看起来很像我的代码。

4

33 回答 33

16

那是因为你没有比较数组中的所有项目,你忽略了最后一个。

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

应该

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

或者

for (var i = 0; i <= str.length - 1; i++)
于 2013-06-30T03:17:20.480 回答
14

One advantage to taking a functional approach to such problems is that you don't even have to keep count

See MDN Array.reduce for more info. (note: reduce needs shim for IE8)

function longer(champ, contender) {
  return (contender.length > champ.length) ? contender : champ;
}

function longestWord(str) {
  var words = str.split(' ');
  return words.reduce(longer);
}

console.log(longestWord("The quick brown fox jumped over the lazy dogs"));

于 2013-06-30T03:47:50.467 回答
5

这是您使用 forEach 的解决方案,这将帮助您避免将来出现错误

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });
    return word;
}
console.log(longestWord("pride and prejudice"));

您最初的问题只是str.length - 1应该是str.length,最初您不会到达数组的最后一个元素

于 2013-06-30T03:27:08.483 回答
4

你有一个-1你的条件,它甚至从不扫描它:

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

应该:

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

演示:http: //jsfiddle.net/LfgFk/

于 2013-06-30T03:15:40.393 回答
3

指数上升至str.length -1

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

所以最后一个字没有处理

尝试:longestWord("Pride AAAAAAAAAAAAAAAAAAAAAAAAA and Prejudice")。你会看到它有效(返回AAAAAAAAAAAAAAAAAAAAAAAAA)。

如果您有疑问,修复它的最简单方法是-1for循环中删除。

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

检查两个版本的演示(有问题的和已修复的):链接在这里

于 2013-06-30T03:15:29.387 回答
2

您可以使用Lo-Dash 之类的库来简化代码:

function longestWord(string) {
    var words = string.split(' ');
    return _.max(words, function(word) { return word.length; });
}
于 2014-06-03T13:06:58.913 回答
2

ForEach 在 FF 中更快,但在 Chrome 中较慢,但对于具有缓存长度和函数应用/调用的循环,在 FF 和 chrome 中都相当快。

希望下面的代码有帮助:

function getLongest (arrStr) {
  var longest = 0, word;

  for(var i=0 , len = arrStr.length ; i < len ; i++){

    if(longest < arrStr[i].length) {
       longest = arrStr[i].length;
       word = arrStr[i];
    }

  }

  return word;
}

function isLongest (str) {
  var arrayStr = str.split(' ');
  return function(fn) {
    return fn.apply(this,[arrayStr]);
  }
}

isLongest("hello aaaaaaaaaaaaaaaaaaaaaaaaa bbb")(getLongest); //aaaaaaaaaaaaaaaaaaaaaaaaa
于 2014-11-08T10:07:33.473 回答
1
for (var i = 0; i < str.length - 1; i++)

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

或者

for (var i = 0; i < str.length; i++)
于 2013-06-30T03:19:11.687 回答
1

我发现这里的 .map 方法很有帮助(如果你想要单词的字符数,而不是单词本身):

 function findLongestWord(str) {   
   var array = str.split(/\s+/);
   var wordLength = array.map(function(i) {
     return i.length;                       
   });   
   var largest = Math.max.apply(Math, wordLength);   
   return largest; 
}
于 2017-06-27T21:36:23.190 回答
1

我将向您推荐这篇很棒的文章,它定义了三种方式:

1 - 使用 FOR 循环查找最长的单词

    function findLongestWord(str) {
  var strSplit = str.split(' ');
  var longestWord = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longestWord){
    longestWord = strSplit[i].length;
     }
  }
  return longestWord;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

2 - 使用 sort() 方法查找最长的单词

function findLongestWord(str) {
  var longestWord = str.split(' ').sort(function(a, b) { return b.length - a.length; });
  return longestWord[0].length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

3 - 使用 reduce() 方法找到最长的单词

function findLongestWord(str) {
  var longestWord = str.split(' ').reduce(function(longest, currentWord) {
    return currentWord.length > longest.length ? currentWord : longest;
  }, "");
  return longestWord.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

当然,如果要获取字符串,它会返回最大单词的长度,只需去掉返回部分的长度即可。

于 2018-10-17T10:23:39.117 回答
1

这能解决问题吗??

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i <= str.length - 1; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    return word;
}

document.write(longestWord("pride and prejudice"));
于 2017-02-07T23:47:27.303 回答
1
function LongestWord(sen) { 

  // code goes here  
  const wordsArray = sen.split('').map(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c<='9')? c : ' ').join('').split(' ').filter(item => item !== '');
  wordsArray.sort((a, b) => a.length < b.length);
  return wordsArray[0]; 

}
于 2019-12-12T11:11:59.537 回答
1
function longestWord(sentence){
 var arr = sentence.match(/[a-z]+/gi);
 arr.sort(function(a, b){
 return b.length - a.length;
});
 return arr[0];
}
longestWord('hello man@#$%');
// ==> output: hello
于 2017-06-01T21:45:58.317 回答
0

谢谢大家,这是固定代码:

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length; i++) {
        var checkedLetters = "";
        for (var j = 0; j < str[i].length; j++) {
            if (/[a-zA-Z]/.test(str[i][j])) {
                checkedLetters += str[i][j];
            }
        if (longest < checkedLetters.length) {
            longest = checkedLetters.length;
            word = checkedLetters;
            }
        }
    }
    return word;
}
于 2013-06-30T14:30:57.937 回答
0

有没有具体原因

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

不是

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

这似乎可能是原因。

于 2013-06-30T03:15:35.203 回答
0

你需要使用:

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

这样它将扫描整个短语

于 2013-06-30T03:21:01.407 回答
0

我会说使用 forEach 循环是最容易理解的版本

function longestWord(sen) {
  big_word = ""
  words = sen.split(" ")
  words.forEach(function(word){
    if (word.length > big_word.length){
        big_word = word
    };
  });
return big_word
};
于 2015-03-26T17:50:01.530 回答
0

这似乎是最简单的方法。

function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;

    str.forEach(function(str) {
        if (longest < str.length) {
            longest = str.length;
            word = str;
        }
    });

return word;

}

于 2013-12-05T18:54:09.220 回答
0
    function findLongestWord(str) {
       let stringArray = str.split(" ");
       stringArray.sort(function(a, b){
          return a.split('').length < b.split('').length;
       })
       return stringArray[0];
    }

    findLongestWord("The quick brown fox jumped over the lazy dog");
于 2018-07-02T08:08:15.477 回答
0

使用 sort() 方法,这将通过某种排序标准对数组的元素进行排序,然后返回该数组的第一个元素的长度,从而返回最长的单词。

function longest(string){
    var longestWord = string.split(' ').sort(function(a,b){
        return b.length - a.length;
    });
    return longestWord[0];
}
于 2017-04-05T10:45:00.790 回答
0

另一种方法是使用排序:

    function longestWord(string) {
        let longest = 0;
        let str = str.split(" ").sort((word1,word2)=>{
        });
        return str[0].length;
   }
   longestWord('I love Python ')
于 2018-03-21T23:16:18.700 回答
0

function sortNumber(a, b) {
return a - b;
}

function findLongestWordLength(str) {
var split = str.split(" ");
var arr=[];
for(var i=0;i<split.length;i++){
  arr.push(split[i].length);
  }
  arr.sort(sortNumber);
  console.log(arr[arr.length-1]);
  return(arr[arr.length-1]);
}

findLongestWordLength("What if we try a super-long word such as otorhinolaryngology");

于 2020-03-20T16:51:33.053 回答
0

快速简单的方法是

let str = "This is longest word";
let longestWord ="";
str.trim().split(" ").map(word=> (word.length > longestWord.length) ? 
longestWord = word : longestWord)
console.log(longestWord)

它还将处理字符串开头和结尾的额外空格

于 2021-09-04T05:09:31.160 回答
0

我认为这更容易

function findLongestWord(str) {
    var longestStr = 0;
    for (var x=0;x<str.split(' ').length;x++){
        if (longestStr < str.split(' ')[x].length){
            longestStr = str.split(' ')[x].length;
        }
    }
    return longestStr;
}
于 2015-08-05T16:52:52.590 回答
0

尝试这个

 function longest(string) {
        var str = string.split(" ");
        var longest = 0;
        var word = null;
        for (var i = 0; i <= str.length - 1; i++) {
            if (longest < str[i].length) {
                longest = str[i].length;
                word = str[i];
            }
        }
        return word;
    }
于 2017-11-24T21:33:21.440 回答
0

const longestWord = string =>
{
    stringArray = string.split(' ').sort(
        (a,b) => b.length - a.length)
    let longestArray= stringArray.filter( word => word.length === stringArray[0].length ) 
    if(longestArray.length === 1){
        console.log(longestArray[0])
    }
    else
    {
        console.log(longestArray)
    }
}
longestWord("Pride and Prejudice")

于 2020-04-02T06:25:00.457 回答
0

这是解决它的另一种方法。

function findLongestWord(str) {
  var result = [];
  
  var one = str.split(" ");
    
   for (var i = 0; i < one.length; i++) {
    result[i] = one[i].length;
     result.reverse().sort(function(a,b) {
       return b-a;
     });   
   }
  return result[0];
}

于 2016-07-16T23:13:44.060 回答
0
// My simple solution.

const findLongestWordLength = str => {
    let array = str.split(" ");
    let longest = 0;

    array.map(e => {
        if (e.length > longest) {
            longest = e.length;
        }
    })
    return longest;
}
于 2020-08-02T11:07:24.827 回答
0

上面的解决方案是不完整的。如果有 r 2 个或更多具有相同长度的单词怎么办。这是一个更好的解决方案:

longest = str => {
  let words = str.split(" ");
  let size = 0;
  let max = [""];

  for (let i = 0; i < words.length; i++) {
    if (words[i].length > size) {
      size = words[i].length;
    }
    if (max[max.length - 1].length < words[i].length) {
      max = [];
      max.push(words[i]);
    } else {
      max = [...max, words[i]];
    }
  }
  return max;
};
于 2019-04-26T03:30:53.130 回答
0

有关有问题的错误检查,请参阅此答案

字符串中最长的单词

使用 for/forEach 循环

function longestWord(str){
  const words = str.split(' ');
  let longWord = "";
  words.forEach((word) => {
    if(word.length > longWord.length) { longWord = word }
  })
  return longWord;
}

使用排序

function longestWord(str) {
  return str.split(' ')
            .sort((a, b) => b.length - a.length)[0];
}

使用减少

function longestWord(str){
  return str.split(' ')
            .reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}

// for loop
function longestWord1(str){
    const words = str.split(' ');
    let longWord = "";
    words.forEach((word) => {
      if(word.length > longWord.length) { longWord = word }
    })
    return longWord;
}

// sort
function longestWord2(str) {
    return str.split(' ').sort((a, b) => b.length - a.length)[0];
}
    
// reduce
function longestWord3(str){
    return str.split(' ').reduce((maxWord, curWord) => curWord.length > maxWord.length ? curWord : maxWord );
}

let text;
text = "What if we try a super-long word such as otorhinolaryngology";
console.log(longestWord1(text));//=> "otorhinolaryngology"
text = "";
console.log(longestWord2(text));//=> ""
text = "What "
console.log(longestWord3(text));//=> "What"
text = "What is pen?"
console.log(longestWord1(text));//=> "What"
text = "three four five six twenty one"
console.log(longestWord2(text));//=> "twenty"
text = ("The quick brown fox jumped over the lazy dog")
console.log(longestWord3(text));//=> "jumped"
  
  

于 2021-09-04T01:32:40.277 回答
0

下面的代码将从字符串中找到最大的单词及其长度。代码是纯 JavaScript 和 html。

function findLongestWord() {
  var str = document.getElementById('inputText').value;
  calculateLength(str);
}

function calculateLength(str) {
  var substring = str.split(" ");
  var minChar = '';
  for (var i = 0; i <= substring.length - 1; i++) {
    if (substring[i].length >= minChar.length) {
      minChar = substring[i];
    }
  }
  document.getElementById('longChar').innerHTML = 'Longest Word: ' + minChar;
  document.getElementById('longCharLength').innerHTML = 'Longest Word length: ' + minChar.length;
}
<!doctype html>
<html lang="en">

<head>
</head>

<body>
  <input type="text" id="inputText"> <br/>
  <button onclick=findLongestWord()>Click to find longest              word</button> <br/>
  <div id="longChar"></div> <br/>
  <div id="longCharLength"></div>
</body>
<script src="longestWord.js"></script>

</html>

于 2018-05-04T09:05:51.017 回答
-1
function longestWord(string) {
   var str = string.split(" ");
   var longest = 0;
   var word = null;
   for (var i=0; i < str.length-1; i++) {
      word = longest < str[i].length ? str[i].length : longest;
         word = str[i];
   }
   return word;
   }
   longestWord('I love Python ')
于 2018-03-21T23:01:07.580 回答
-2

检查这是否有帮助:

function longestWord(string){
  var str = string.split(" ");
  var longest = 0;
  var word = null;
  for(var i=0; i < str.length; i++){
    if(longest < str[i].length){
      longest=str[i].length;
      word=str[i];
    }
  }
  return word;
}
于 2017-11-18T21:53:56.950 回答