gpt4 book ai didi

javascript - Math.max 引用的最长单词

转载 作者:行者123 更新时间:2023-12-02 07:20:06 24 4
gpt4 key购买 nike

我见过很多解决方案,但不是我尝试解决这个问题的方法。- 我试图在空格处断开字符串并将所有单词存储在变量单词中。我使用 for 循环来计算每个单词中的字母表,并将每个单词一个一个地存储在 alphabetsInWord 中,并将每个单词的长度插入数组。循环完成后,每个单词的长度存储在称为数组的数组中。由于数组中的值是数字,所以我想在数组上应用 Math.max 来查找 logestWord 的值,但它不返回一个。我有 console.log statments 在那里检查但不是必需的。有人可以帮我如何让它工作吗?我认为看看这种方式是否也有效会很有趣。

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

最佳答案

使用 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);

或者,您可以使用 native 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);

使用资源:


关于javascript - Math.max 引用的最长单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363808/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com