在`forEach`函数里面`return`关键字是什么意思? [英] What does `return` keyword mean inside `forEach` function?

查看:386
本文介绍了在`forEach`函数里面`return`关键字是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$('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>

我的问题:虽然我打电话给返回,为什么它仍会提示下一个号码?就像:忽略下面的代码并继续下一个元素

My question: Why does it still alert next number although I call return? Just like: Ignore the code below and continue with next element

推荐答案

来自 Mozilla开发者网络


除了抛出异常之外,没有办法停止或破坏 forEach()循环。如果您需要这样的行为, forEach()方法是错误的工具。

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:

  • A simple loop
  • A for...of loop
  • Array.prototype.every()
  • Array.prototype.some()
  • Array.prototype.find()
  • Array.prototype.findIndex()

其他数组方法: every() some() find() findIndex() 使用谓词返回truthy值来测试数组元素,以确定是否需要进一步迭代。

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.

这篇关于在`forEach`函数里面`return`关键字是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆