【问题标题】:Longest word in quote with Math.max用 Math.max 引用的最长单词
【发布时间】:2018-01-21 04:53:30
【问题描述】:

我已经看到了许多不是我试图解决这个问题的方式的解决方案。 - 我试图在空格处打破字符串并将所有单词存储在变量单词中。 我使用 for 循环来计算每个单词中的字母,并将每个单词一个一个地存储在 alphabetsInWord 中,并将每个单词的长度推入数组中。循环完成后,每个单词的长度存储在称为数组的数组中。由于数组中的值是数字,所以我想在数组上应用 Math.max 以找到 logestWord 的值,但它不返回一个。我在那里有 console.log 语句可以检查,但不是必需的。有人可以帮我如何使它工作。我认为看看这种方式是否也有效。

    function findLongestWord(str) {
      var word = str.split(" ");
      var array=[];
      console.log(word);
         for(i=0; i <= word.length; i++){
            var alphabetsInWord = word[i];
            array.push(alphabetsInWord.length);                 
            console.log(array);
           //console.log(Math.max(array));
         }
     var longestWord = Math.max(array);
     return longesWord;
     console.log(longestWord); 

   } 

 findLongestWord("The quick brown fox jumped over the lazy dog");

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    使用 ES6 语法,你可以这样做:

    var str = "The quick brown fox jumped over the lazy dog";
    
    var wordLengths = str.split(" ").map(w => w.length);
    
    const maxLength = Math.max(...wordLengths);
    
    console.log(maxLength);

    您也可以使用本机 forEach()sort() 方法来实现此目的:

    var str = "The quick brown fox jumped over the lazy dog";
    var words = str.split(" ");
    var wordLengths = [];
    
    words.forEach(function(word) {
      wordLengths.push(word.length);
    });
    wordLengths.sort(function(a, b) {
      return a - b;
    });
    
    const maxLength = wordLengths[wordLengths.length - 1];
    console.log(maxLength);

    使用资源:


    【讨论】:

    • 感谢您的所有帮助!研究解决一个问题的各种方法总是很有趣。
    【解决方案2】:

    for 循环不应迭代到 word.length,因为数组的索引从 0 开始;将&lt; 替换为&lt;= 以迭代到word.length - 1。将.apply()Math.max() 一起使用,它不期望将数组作为参数传递,Math 设置为thisconsole.log() 不会在 return 语句之后运行。

    function findLongestWord(str) {
      var word = str.split(" ");
      var array = [];
      for (var i = 0; i < word.length; i++) {
        var alphabetsInWord = word[i];
        array.push(alphabetsInWord.length);
      }
      var longestWord = Math.max.apply(Math, array);
      return longestWord;
    }
    
    console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2021-04-20
      • 2019-04-28
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      相关资源
      最近更新 更多