JavaScript:使用 forEach 查看数组是否包含特定的数值

Pin*_*ts0 2 javascript arrays element input function

我有下面的代码。在这种情况下,我有意尝试使用 forEach。

function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)
Run Code Online (Sandbox Code Playgroud)

我期望代码返回 true,因为 el 值 3 在数组中。但它返回未定义。我究竟做错了什么?

Cod*_*iac 5

forEach返回任何内容(意味着 undefined ),您可以使用一些

function check(arr, el) {
  return arr.some( element => element === el)
}

console.log(check([1, 2, 3, 4, 5], 3))
Run Code Online (Sandbox Code Playgroud)

如果您想使用而forEach不是使用变量来存储值,然后再从函数中返回

function check(arr, el) {
  let found = false
  
  arr.forEach((element) => {
    if (element === el && !found){
      found = true
    }
  })
  return found
}



console.log(check([1, 2, 3, 4, 5], 3))
Run Code Online (Sandbox Code Playgroud)