因此,我正在尝试使用forEach编写一个名为count(arr,callback)的函数。
理论上,它应该返回其回调为true的元素的数量。
count([1, 2, 3, 4], (e) => e === 3)
期望:1但得到:0
count([1, 2, 3, 4], (e) => e > 1)
预期:3,但得到:0
count([2, 1, 4, 5, 2, 8], (e) => e === 2)
期望:2但得到:0
这是我正在运行的代码:
function count(arr, callback) {
let values = 0;
arr.forEach(callback) ? values++ : values;
return values;
}
function count(arr, callback) {
let values = 0;
arr.forEach(item => callback(item) ? values++ : values);
return values;
}
console.log(count([1, 2, 3, 4], (e) => e === 3))
console.log(count([1, 2, 3, 4], (e) => e > 1))
console.log(count([2, 1, 4, 5, 2, 8], (e) => e === 2))
使用filter
:
const count = (arr, c) => arr.filter(c).length;
console.log(count([1, 2, 3, 4], (e) => e === 3))
console.log(count([1, 2, 3, 4], (e) => e > 1))
console.log(count([2, 1, 4, 5, 2, 8], (e) => e === 2))
forEach
忽略其回调的返回值。使用reduce
代替:
const count = (arr, cb) => arr.reduce((a, item) => a + cb(item), 0);
console.log(count([1, 2, 3, 4], (e) => e === 3))
console.log(count([1, 2, 3, 4], (e) => e > 1))
console.log(count([2, 1, 4, 5, 2, 8], (e) => e === 2))