`forEach` 函数中的 `return` 关键字是什么意思? [英] What does `return` keyword mean inside `forEach` function?
问题描述
$('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
,它仍然提示下一个号码?就像:忽略下面的代码并继续下一个元素
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, theforEach()
method is the wrong tool.
提前终止可以通过:
- 一个简单的循环
- A
for
...of
循环 Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
其他数组方法:every()
, some()
, find()
和 findIndex()
使用返回真值的谓词测试数组元素,以确定是否需要进一步迭代.
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屋!