我遵循3下的代码。使用reduce()方法查找最长的单词 source
为什么结果显示2而不是5?我的逻辑如下:
- longest.length = 0 ("") > currentWord.length = 5 (howss) -> false, 输出 5
- longest.length = 5 (howss) > currentWord.length = 5 (fuund) -> false, 输出 5 (fuund)
- longest.length = 5 (fuund) > currentWord.length = 2 (se) -> true, 输出 5 (fuund)
let arr = ['howss', 'fuund', 'se']
let longestLength = arr.reduce((longest, currentWord) =>
longest.length > currentWord.length ?
longest.length : currentWord.length , "")
console.log(longestLength)
另外,如何将第 97 行移动到与下图中第 92 行相同的位置?当前的格式显示第 97 行是第 93 行的一部分。但是代码运行良好
最佳答案
reduce
函数中的累加器应该是一个数字
,表示迄今为止最长单词的长度,初始设置为零:
const arr = ['howss', 'fuund', 'se'];
const longestLength = arr.reduce((longestLen, currentWord) =>
longestLen > currentWord.length ? longestLen : currentWord.length
, 0);
console.log(longestLength);
如果你想设置为代表最长单词的字符串
,则需要先计算它,然后在循环结束后获取长度
:
const arr = ['howss', 'fuund', 'se'];
const longestLength = arr.reduce((longestWord, currentWord) =>
longestWord.length > currentWord.length ? longestWord : currentWord
, "").length;
console.log(longestLength);
关于javascript - arr.reduce 显示最短长度而不是最长长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68974843/