Javascript `forEach` 函数中的 `return` 关键字是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34653612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does `return` keyword mean inside `forEach` function?
提问by Tan
$('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
我的问题:为什么尽管我打电话,它仍然提醒下一个号码return
?就像:忽略下面的代码并继续下一个元素
回答by squaleLis
From the 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, theforEach()
method is the wrong tool.Early termination may be accomplished with:
- A simple loop
- A
for
...of
loopArray.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
The other Array methods:
every()
,some()
,find()
, andfindIndex()
test the array elements with a predicate returning a truthy value to determine if further iteration is required.
forEach()
除了抛出异常之外,没有其他方法可以停止或中断循环。如果您需要这种行为,那么该forEach()
方法就是错误的工具。提前终止可以通过以下方式完成:
- 一个简单的循环
- 一个
for
...of
循环Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
其他 Array 方法:
every()
、some()
、find()
和findIndex()
使用返回真值的谓词测试数组元素以确定是否需要进一步迭代。
回答by Ronen Cypis
The return
exits the currentfunction, but the iterations keeps on, so you get the "next" item that skips the if
and alerts the 4...
在return
退出当前功能,但反复不断,所以你得到的“下一个”项目是跳过if
和警报的4 ...
If you need to stop the looping, you should just use a plain for
loop like so:
如果你需要停止循环,你应该for
像这样使用一个简单的循环:
$('button').click(function () {
var arr = [1, 2, 3, 4, 5];
for(var i = 0; i < arr.length; i++) {
var n = arr[i];
if (n == 3) {
break;
}
alert(n);
})
})
You can read more about js break & continue here: http://www.w3schools.com/js/js_break.asp
您可以在此处阅读有关 js break & continue 的更多信息:http: //www.w3schools.com/js/js_break.asp