【问题标题】:Using a for-loop to find a string in an array is working, but forEach() does not here. Why and how to correct?使用 for 循环在数组中查找字符串是有效的,但 forEach() 在这里不行。为什么以及如何纠正?
【发布时间】:2015-08-18 21:13:04
【问题描述】:

通过一些 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?

【问题讨论】:

标签: javascript arrays for-loop foreach


【解决方案1】:

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";
  });
}

filter() 并检查结果中的length

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

【讨论】:

  • 知道了!谢谢,这对我来说很有意义。
【解决方案2】:

您的第二个 hello_exists 函数没有返回任何内容。看起来可能是因为您在其中有“返回”,但那是在 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

【讨论】:

    【解决方案3】:

    如果您想像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
        }
    }
    

    【讨论】:

    • 感谢 pdenes,以这种方式检查 forEach 非常有帮助。
    猜你喜欢
    • 1970-01-01
    • 2021-11-06
    • 1970-01-01
    • 2017-06-24
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多