使用.reduce()的统计函数返回数组时附带undefined值问题排查
问题根因
那个多出来的undefined是函数的默认返回值:
- JavaScript里只要函数没写
return明确返回内容,执行完就会默认返回undefined - 你现在写的函数最后一行是
console.log(mostCommonGenres),这行只是把统计好的数组打到控制台,根本没把结果返回出去 - 要是你是直接在控制台跑
console.log(findMostCommonGenres(books))这种调用,流程是:先跑函数,函数内部的console.log先打出正确的统计数组,函数跑完没返回值就给外层丢了个undefined,外层的console.log拿到这个undefined就又打了一行,正好就是你看到的输出效果。
修复方案
把函数最后那行console.log换成return返回结果就行,别在函数里面写死打印逻辑,要打印的话在外面拿了返回值再打。
修正后的完整代码:
function findMostCommonGenres(books) { const mostCommonGenres = books.reduce((genres, book) => { const genreObj = genres.find(currGenre => currGenre.name === book.genre); !genreObj ? genres.push({ name: book.genre, count: 1, }) : genreObj.count++; return genres; }, []); mostCommonGenres.sort((genA, genB) => genB.count - genA.count); mostCommonGenres.splice(5); // 原console.log替换为返回结果 return mostCommonGenres; } // 外部调用示例 const genreStats = findMostCommonGenres(bookList); console.log(genreStats); // 这里只会输出正确的统计数组,不会再出现undefined
补充说明:你写的分类统计、降序排序、截取前5项的逻辑本身完全符合需求,没有问题,唯一的bug就是缺少返回值。
内容的提问来源于stack exchange,提问作者0xcatbot
相关产品推荐
相关产品推荐

