使用for循环在数组中查找字符串是有效的,但是这里的forEach()不起作用.为什么以及如何纠正

Using a for-loop to find a string in an array is working, but forEach() does not here. Why and how to correct?

本文关键字:forEach 不起作用 为什么 何纠正 这里 数组 循环 for 查找 使用 有效      更新时间:2023-09-26

通过一些javascript数组练习来巩固我的理解。遇到了一个练习,我可以使用for循环轻松解决,但不使用forEach()方法。为什么会发生这种情况,我该如何纠正这种情况?

下面列出了练习问题,以及我使用下面两种方法的代码:"编写一个函数,接受一个数组的值,并返回一个布尔值,表示数组中是否存在单词"hello"。"

function hello_exists(array){
  for(i = 0; i < array.length; i++){
    if(array[i] === "hello"){
      return true
    }
  }
}
var my_arr = ["some", "hello", "is", "cat"]
hello_exists(my_arr) // returns true as expected
function hello_exists(array){
  array.forEach(function(val){
    if(val === "hello") {
      return true
    }
  })
}
var my_arr = ["some", "hello", "is", "cat"]
hello_exists(my_arr) // returns undefined. not sure why?

forEach中返回true实际上并没有返回值给调用者,并且没有效果。

传递给forEach的回调被指定在迭代中执行一组操作(不返回任何东西)

使用一个变量在forEach完成执行后返回

function hello_exists(array){
  var exists = false;
  array.forEach(function(val){
    if(val == "hello"){
         exists = true;
    }
  });
  return exists;
}
作为一种替代方法,您可以使用some()
function hello_exists(array){
  return array.some(function(val){
    return val == "hello";
  });
}

过滤器()检查length的结果

function hello_exists(array){
  return array.filter(function(val){
    return val == "hello";
  }).length > 0;
}

第二个hello_exists函数没有返回任何东西。它可能看起来是这样的,因为你有'return'在那里,但那是在forEach函数。

在第二个示例中,您需要为hello_exists函数返回一些东西。像这样的代码可以工作

function hello_exists(array){
  var isTrue = false
  array.forEach(function(val){
    if(val === "hello") {
      isTrue = true
    }
  })
  return isTrue
}
var my_arr = ["some", "hello", "is", "cat"]
hello_exists(my_arr) // true

想象一下forEach:

的简化实现,也可以帮助理解发生了什么:
function forEach(array, fn) {
    var i;
    for (i = 0; i < array.length; i++) {
        fn(arr[i]);  // forEach doesn't care about what the function returns
    }
}