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

JavaScript: Use forEach to see if array contains a specific number value

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

function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)

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

forEach don't return anything ( means undefined ), you can use some

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

console.log(check([1, 2, 3, 4, 5], 3))

如果你想使用 forEach 而不是使用变量来存储值,而不是 return 稍后从函数

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

只是为了使用 OP 的上下文。因为必须使用 forEach。

function check(arr, el) {

  let found = false;

  arr.forEach((element) => {
    console.log(element)
    if (element === el){
        found = true;
    }
  })

  return found;
}

不能在 forEach 语句中使用 return

注意:此答案仅 ,因为您需要使用 forEach。 通常你总是使用 some().

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



console.log( check([1, 2, 3, 4, 5], 3));

如果您想使用 forEach,您需要在找到匹配项时更新一个变量。 Array.forEach by default returns undefined. There is no build in way to break out of the forEach.

因为您只是在寻找简单的元素匹配,只需使用 Array.includes:

let check = (arr, el) => arr.includes(el)

console.log(check([1, 2, 3, 4, 5], 3))

Array.some 给你一个迭代器函数,在这种情况下你真的不需要。

Array.forEach:

function check(arr, el) {
  let result = false
  arr.forEach((element) => {
    if (element === el) {
      result = true  // <-- update the result on match
    }
  })
  return result  // <-- return the result
}

console.log(check([1, 2, 3, 4, 5], 3))