javascript - forEach 内部和 forEach 之后的条件回调,但似乎没有按预期返回?

标签 javascript foreach

function(callback) {
  console.log(1, '*****');
  var array = ['hello'];
  array.forEach(element) {
    if (element === 'hello') {
      console.log(2, '*****');
      return callback(true); // doesn't end or return here. not sure why?
    }
  }
  console.log(3, '*****');
  return callback(false);
}

//current output
1 '*****'
2 '*****'
3 '*****'

//Desired output 
1 '*****'
2 '*****'

为什么即使满足了if条件,控制流程还是一路结束?为什么它不立即返回回调?

最佳答案

return 语句实际上不会返回到 function(callback),而是将值返回到 forEach 函数。

From MDN docs: Note: There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behaviour, the .forEach() method is the wrong tool, use a plain loop instead. If you are testing the array elements for a predicate and need a boolean return value, you can use every() or some() instead.

关于javascript - forEach 内部和 forEach 之后的条件回调,但似乎没有按预期返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33824034/

相关文章:

javascript - 如何替换数组中元素的实例?

javascript - 如何获取显示在谷歌搜索右侧的图像链接

java - 如何仅将不同的元素从一个 arrayList 复制到另一个 ArrayList

javascript - 循环数组以修改值(JavaScript 到 PHP 并返回到 JavaScript)

PHP, "Foreach"使用 3 个数组

javascript - NodeJS 中找不到另一个 .js 文件中定义的函数

javascript - 前 3 名浏览器中的早期 appendChild hell

javascript - 查找所有子组的递归函数

java - 在 foreach 循环中选择特定项目?

Javascript:foreach 跳过第一个索引 (0)