javascript - `return` 关键字在 `forEach` 函数中意味着什么?

标签 javascript arrays

$('button').click(function () {
   [1, 2, 3, 4, 5].forEach(function (n) {
      if (n == 3) {
         // it should break out here and doesn't alert anything after
         return false
      }
      alert(n)      
   })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>

我的问题:为什么在我调用 return 时它仍然提醒下一个号码?就像:忽略下面的代码并继续下一个元素

最佳答案

来自Mozilla Developer Network :

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

关于javascript - `return` 关键字在 `forEach` 函数中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653612/

相关文章:

sql - Ruby on Rails - 迁移、唯一列和索引(使用数组)

java - 一维数组中的三角矩阵 get()

c++ - 文本文件中的值未写入二维数组?

arrays - 查找代码的时间复杂度

javascript - Javascript 中的奇怪字符导致它无法加载

javascript - 将固定背景图像和滚动前部 div 添加到 html 页面

python - 为什么 "None"与 "np.newaxis"具有相同的效果?

javascript - 我应该用默认值初始化 JavaScript 中的变量吗?

javascript - 使用 Javascript 将对象数组转换为对象

javascript - php 中的计数查询