javascript - arr.reduce 显示最短长度而不是最长长度

标签 javascript reduce

我遵循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 行的一部分。但是代码运行良好

line 97 classified as part of line 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/

相关文章:

javascript - 通过 user_id 减少对象数组并对某些值求和

recursion - 为什么 reduce 会在 Clojure 中给出 StackOverflowError?

arrays - 在给定的排列中找到缺失的元素

python减少浮点错误

javascript - Backbone.js 和非模型对象

javascript - 图像覆盖网络视频

javascript - CDN 上的多个文件与本地一个文件

javascript - 如何检查打开的窗口是否已用 javascript 关闭?

javascript - 排序不适用于下拉菜单

cuda - Thrust:如何直接控制算法调用的执行位置?