Javascript reduce() 查找字符串中最短的单词
Javascript reduce() to find the shortest word in a string
我有一个函数可以找到字符串中最长的单词。
function findLongestWord(str) {
var longest = str.split(' ').reduce((longestWord, currentWord) =>{
return currentWord.length > longestWord.length ? currentWord : longestWord;
}, "");
return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));
我很难将其转换为找到最短的单词。为什么我不能直接将 currentWord.length > longestWord.length
更改为 currentWord.length < longestWord.length
?
您需要为reduce
函数提供一个初始值,否则为空字符串是最短的单词:
function findShortestWord(str) {
var words = str.split(' ');
var shortest = words.reduce((shortestWord, currentWord) => {
return currentWord.length < shortestWord.length ? currentWord : shortestWord;
}, words[0]);
return shortest;
}
console.log(findShortestWord("The quick brown fox jumped over the lazy dog"));
虽然使用 reduce
,但 initialValue
是可选的,如果未提供,则您的第一个元素将用作 initialValue
。所以,在你的情况下,你只需要删除你的 ""
:
function findLongestWord(str) {
var longest = (typeof str == 'string'? str : '')
.split(' ').reduce((longestWord, currentWord) =>{
return currentWord.length < longestWord.length ? currentWord : longestWord;
});
return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog")); // The
我是这样编码的
const findLongestWord = str => {
return typeof str === 'string'
? str.split(' ').reduce((sw, lw) => lw.length < sw.length ? lw :sw)
: '';
}
console.log(findLongestWord('The quick brown fox jumps over the lazy dog.')); //'The'
我有一个函数可以找到字符串中最长的单词。
function findLongestWord(str) {
var longest = str.split(' ').reduce((longestWord, currentWord) =>{
return currentWord.length > longestWord.length ? currentWord : longestWord;
}, "");
return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog"));
我很难将其转换为找到最短的单词。为什么我不能直接将 currentWord.length > longestWord.length
更改为 currentWord.length < longestWord.length
?
您需要为reduce
函数提供一个初始值,否则为空字符串是最短的单词:
function findShortestWord(str) {
var words = str.split(' ');
var shortest = words.reduce((shortestWord, currentWord) => {
return currentWord.length < shortestWord.length ? currentWord : shortestWord;
}, words[0]);
return shortest;
}
console.log(findShortestWord("The quick brown fox jumped over the lazy dog"));
虽然使用 reduce
,但 initialValue
是可选的,如果未提供,则您的第一个元素将用作 initialValue
。所以,在你的情况下,你只需要删除你的 ""
:
function findLongestWord(str) {
var longest = (typeof str == 'string'? str : '')
.split(' ').reduce((longestWord, currentWord) =>{
return currentWord.length < longestWord.length ? currentWord : longestWord;
});
return longest;
}
console.log(findLongestWord("The quick brown fox jumped over the lazy dog")); // The
我是这样编码的
const findLongestWord = str => {
return typeof str === 'string'
? str.split(' ').reduce((sw, lw) => lw.length < sw.length ? lw :sw)
: '';
}
console.log(findLongestWord('The quick brown fox jumps over the lazy dog.')); //'The'