[removed] find longest word in a string

前端 未结 30 2538
余生分开走
余生分开走 2020-11-27 03:50
function longestWord(string) {
    var str = string.split(\" \");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length - 1; i++) {
                


        
相关标签:
30条回答
  • 2020-11-27 04:20

    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"));

    0 讨论(0)
  • 2020-11-27 04:21

    You need to use:

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

    That way it will scan the entire phrase

    0 讨论(0)
  • 2020-11-27 04:22

    Is there a specific reason

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

    isn't

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

    That seems like it could be the cause.

    0 讨论(0)
  • 2020-11-27 04:24

    This seems to be the easiest way to do this.

    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;
    

    }

    0 讨论(0)
  • 2020-11-27 04:25

    Here is one other way to solve it.

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

    0 讨论(0)
  • 2020-11-27 04:27

    Here this is your solution with a forEach, this will help you avoid the error in the future

    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"));
    

    Your original problem was just the str.length - 1 should have just been str.length, originally you wouldn't have gotten to the last element of the array

    0 讨论(0)
提交回复
热议问题