js:找出一个字符串中最长单词的长度和最长单词

代码

function findWordLongest(str){
            var newArr = str.split(' ')//从空格的地方隔开组成一个新的数组
            var tempArr = []
            for(var i=0;i<newArr.length;i++){
                tempArr.push(newArr[i].length)
            }
            var maxLengthStr = tempArr.sort(function(a,b){//得到最长的单词的长度
                return b-a    // b-a是降序。a-b是升序
            })[0]
            var maxLengthWorl = []//最长的单词
            newArr.forEach(item=>{
                if(item.length==maxLengthStr){
                    maxLengthWorl.push(item)
                }
            })
            var result = new Array(maxLengthStr,maxLengthWorl);
            return result
        }
        var result = findWordLongest('The abc quick abcdefghig fox jumped over the lazy dog')

结果

原文地址:https://www.cnblogs.com/zhangying0518/p/14148845.html