关于JavaScript的查询(回调和forEach)

问题描述 投票:1回答:3

因此,我正在尝试使用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;
}
javascript callback conditional-operator
3个回答
0
投票

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))

1
投票

使用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))

0
投票

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))
© www.soinside.com 2019 - 2024. All rights reserved.