gpt4 book ai didi

javascript - 尝试使用 reduce 查找偶数和奇数计数

转载 作者:行者123 更新时间:2023-11-30 09:18:02 25 4
gpt4 key购买 nike

我正在尝试使用 reduce 解决以下问题,但我无法获得对象中偶数和奇数的正确计数。

有人可以指导我了解我的代码有什么问题吗?

Create a function countBy that accepts an array and a callback, andreturns an object. countBy will iterate through the array and performthe callback on each element. Each return value from the callback willbe saved as a key on the object. The value associated with each keywill be the number of times that particular return value was returned

function countBy(arr, fn) {
return arr.reduce(function(acc, nums) {
// console.log(nums);
let oddCount = 0
let evenCount = 0
console.log(nums, fn(nums))
if(fn(nums) === "even"){
evenCount++;
acc['even'] = evenCount;
} else {
oddCount++;
acc['odd'] = oddCount;
}
return acc
}, {}, 0)
}

function evenOdd(n) {
if (n % 2 === 0) return "even";
else return "odd";
}

var nums = [1, 2, 3, 4, 5];
console.log(countBy(nums, evenOdd)); // should log: { odd: 3, even: 2 }

最佳答案

您正在将 oddCountevenCount 初始化为 0 inside reduce 回调,所以在每次迭代中,你的

evenCount++;
acc['even'] = evenCount;

只会将 evenCountoddCount 递增到 1。相反,在回调之外初始化计数,以便对它们的更改在 reduce 回调的多次调用中保持不变:

function countBy(arr, fn) {
let oddCount = 0
let evenCount = 0
return arr.reduce(function(acc, nums) {
// console.log(nums);
console.log(nums, fn(nums))
if (fn(nums) === "even") {
evenCount++;
acc['even'] = evenCount;
} else {
oddCount++;
acc['odd'] = oddCount;
}
return acc
}, {}, 0)

}

function evenOdd(n) {
if (n % 2 === 0) return "even";
else return "odd";
}
var nums = [1, 2, 3, 4, 5];
console.log(countBy(nums, evenOdd)); // should log: { odd: 3, even: 2 }

或者,您可以通过检查累加器上已有的属性值来完全避免外部变量:

const countBy = (arr, fn) => arr.reduce((acc, num) => {
const prop = fn(num);
acc[prop] = (acc[prop] || 0) + 1;
return acc;
}, {});

function evenOdd(n) {
if (n % 2 === 0) return "even";
else return "odd";
}
var nums = [1, 2, 3, 4, 5];
console.log(countBy(nums, evenOdd)); // should log: { odd: 3, even: 2 }

关于javascript - 尝试使用 reduce 查找偶数和奇数计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53689885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com