javascript - Array.prototype.reduce() 在 JavaScript 中返回错误的输出
问题描述
function getCount(objects) {
return objects.reduce((count, o) => {
return count++;
}, 0);
}
console.log(getCount([{x: 1, y: 1},{x: 2, y: 2}]));
结果:0
但我希望它返回 2。
解决方案
像这样更改您的代码
function getCount(objects) {
return objects.reduce((count, o) => {
return count+=1;
}, 0);
}
或者
function getCount(objects) {
return objects.reduce((count, o) => {
return count+1;
}, 0);
}
推荐阅读
- oozie - Oozie 让其他分叉操作继续,以防一个失败但在加入后终止
- angular - 使用大量子组件优化 Angular 组件
- hibernate-search - 如何在休眠搜索中查询空集合
- javascript - 如何将以下字符串拆分为可用于填充 html 表的数组
- clang - 如何使用 c++ API 获取与 ClangAST 中的节点关联的指针?
- visual-studio-code - VS Code + Prettier 不使用 printWidth 设置?
- python - 如何防止 Pandas 将日期时间转换为 datetime64
- javascript - JavaScript 函数赋值
- python - 在终端中运行 Python 程序时出错
- arduino - 将模拟值映射到条件内的 pwm 信号