$(“按钮”)。点击(函数(){ [1,2,3,4,5]。forEach(函数(n) { 如果(n == 3) { //它应该在这里爆发,之后不提醒任何东西 返回假 } 警报(n) }) }) < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < >按钮点击我> < /按钮

我的问题是:为什么当我呼叫返回时,它仍然提醒下一个号码?就像:忽略下面的代码,继续下一个元素


当前回答

返回函数退出当前函数,但迭代仍在继续,因此您将获得跳过if并警告4…

如果你需要停止循环,你应该使用一个简单的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);
   })
})

你可以在这里阅读更多关于js break & continue的内容:http://www.w3schools.com/js/js_break.asp

其他回答

来自Mozilla开发者网络:

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() 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.

返回函数退出当前函数,但迭代仍在继续,因此您将获得跳过if并警告4…

如果你需要停止循环,你应该使用一个简单的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);
   })
})

你可以在这里阅读更多关于js break & continue的内容:http://www.w3schools.com/js/js_break.asp