要求:
在句子中找出最长的单词,并返回它的长度。
函数的返回值应该是一个数字。
样本:
findLongestWord("The quick brown fox jumped over the lazy dog") 应该返回一个数字
findLongestWord("The quick brown fox jumped over the lazy dog") 应该返回 6.
findLongestWord("May the force be with you") 应该返回 5.
findLongestWord("Google do a barrel roll") 应该返回 6.
findLongestWord("What is the average airspeed velocity of an unladen swallow") 应该返回 8.
findLongestWord("What if we try a super-long word such as otorhinolaryngology") 应该返回 19.
解法:
function findLongestWord(str) {
var strArr = str.split(" ");
var length = 0;
for(var i=0;i<strArr.length;i++){
if(strArr[i].length>length)length=strArr[i].length;
}
return length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

本文介绍了一个JavaScript函数,用于在给定的字符串中找到最长的单词并返回其长度。通过将字符串分解为字符数组并遍历比较,实现了对字符串中每个单词长度的测量。

8万+

被折叠的 条评论
为什么被折叠?



