大家好,所以我有这个练习,我需要检查哪个字符串是数组中最长的。这段代码有效,但我不能 100% 确定是否理解它的减少部分。所以如果我错了,请纠正我 - 当减少开始时,总数是“the”,num是“quick”,因为“the”比“quick”短,所以返回“quick”。那么下次总计是“快速”而 num 是“棕色”?
function findLongestWord(str) {
var arr = str.split(' ');
var longest = arr.reduce(function(total, num){
if(total.length>num.length){
return total;
} else {
return num;
}
});
return longest.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
最佳答案
function findLongestWord(str) {
var arr = str.split(' ');
var longest = arr.reduce(function(total, num){
console.log('total :', total,'num :', num);
if(total.length>num.length){
return total;
} else {
return num;
}
});
return longest.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
它不断地逐对取出数组的元素并存储总共较大的变量,要比较的较新的字符串是num,因为我们以成对的方式进行比较,所以它会返回最长的字符串
关于javascript - 减少并检查最长的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45652686/