JavaScript寻找最长的单词算法挑战

返回提供的句子中最长的单词的长度。

返回值应该是一个数字。

function findLongestWord(str) {
    var arr = str.split(" ");//空格为界限拆分字符串为数组["The","quick","brown","fox","jumped","over","the","lazy","dog"]
    arr.sort(function compare(x,y){ //用sort()方法对数组进行排序
        return y.length-x.length;//(按数组每项{即单词长度}降序排序)
    });
return arr[0].length;//取第一项为单词长度最长一项
}

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

在Javascript的数组Array中,sort()函数主要使用来对数组的元素进行排序。

比较函数:

function compare(value1, value2){
    if(value1 < value2){
        return -1;
    }else if(value1 > value2){
        return 1;
    }else{
        return 0;
    }
}//升序
function compare(value1, value2){
retuen value1 - value2;}//升序

//-------------------------------------------------------------------------
function compare(value1, value2){
    if(value1 < value2){
        return 1;
    }else if(value1 > value2){
        return -1;
    }else{
        return 0;
    }
}//降序
function compare(value1, value2){
retuen value2 - value1;}//降序

测试用例:

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.

猜你喜欢

转载自blog.csdn.net/weixin_42526091/article/details/84580339