首页 > 解决方案 > 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。

标签: javascriptarrays

解决方案


像这样更改您的代码

function getCount(objects) {
    return objects.reduce((count, o) => {
        return count+=1;
    }, 0);
}

或者

function getCount(objects) {
    return objects.reduce((count, o) => {
        return count+1;
    }, 0);
}

推荐阅读