已关闭,此问题为opinion-based。目前不接受答复。
**想改善这个问题吗?**更新问题,以便editing this post可以用事实和引用来回答。
2天前关闭。
Improve this question
function findLongestWordLength(str) {
//Creating the regex and adding the solution in the array
let word = [];
let regex = /[A-Za-z]+\S/g;
let result = str.match(regex);
word.push(result);
//Iterating the array using forEach
let currentWord = 0;
word.forEach((element) => {
element.forEach((element2) => {
let longestWord = element2.length;
if (currentWord < longestWord) {
currentWord = longestWord;
}
});
});
//It returns the longest word (the length of that word)
return currentWord;
}
console.log(
findLongestWordLength("The quick brown fox jumped over the lazy dogs")
);
这是你在JavaScript中解决这个问题的最短方法吗?它可以用更少的代码行来编写吗?或者更像一行代码,使用数组方法,如map,filter或reduce?另外,是否有更短/更简单的regEx可以用于将字符串拆分为单词?
1条答案
按热度按时间xnifntxz1#
稍微短一点,返回最长的单词:
或者,如果你只想要最长单词的长度(你的主题说最长单词,但你的代码说最长单词长度):