Write a javascript function count(arr, callback). It should return the number of elements for which the callback(an arrow function) is true

huangapple go评论81阅读模式
英文:

Write a javascript function count(arr, callback). It should return the number of elements for which the callback(an arrow function) is true

问题

Here's the translated code part:

例如:
``` lang-js
count([2, 1, 4, 5, 2, 8], (e) => e === 2)  // 预期结果: 2
count([1, 2, 3, 4], (e) => e > 1)          // 预期结果: 3

还需要使用 forEach

我有以下代码:

function count(arr, callback) {
  let values = 0
  arr.forEach(cb ? values++ : values + 0)
  return values
}

然而,这并不起作用。有什么建议吗?


<details>
<summary>英文:</summary>

For example: 
``` lang-js
count([2, 1, 4, 5, 2, 8], (e) =&gt; e === 2)  // Expected: 2
count([1, 2, 3, 4], (e) =&gt; e &gt; 1)          // Expected: 3

It is also necessary to use forEach

What I have:

function count(arr, callback) {
  let values = 0
  arr.forEach(cb ? values++ : values + 0)
  return values
}

This doesn't work though. Any advice?

答案1

得分: 6

首先,forEach 需要传递一个函数。

arr.forEach((item) => { 
...
})

另外,你的变量 cb 没有定义。你的参数被称为 callback

我已经使用这些更改更新了你的示例:

function count(arr, callback) {
  let values = 0
  arr.forEach((item) => {
    callback(item) ? values++ : values + 0
  })

  return values
}
英文:

Firstly, forEach needs to be passed a function.

arr.forEach((item) =&gt; { 
...
})

Also, your variable cb is not defined. Your parameter is called callback

I have updated your example with these changes:

function count(arr, callback) {
  let values = 0
  arr.forEach((item) =&gt; {
    callback(item) ? values++ : values + 0
  })

  return values
}

答案2

得分: 0

一个行代码解决方案:

const count = (array, callback) => array.filter(callback).length

英文:

One line solution:

const count = (array, callback) =&gt; array.filter(callback).length

huangapple
  • 本文由 发表于 2020年1月3日 23:45:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581412.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定