Javascript For 循环回调?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5602427/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:59:45  来源:igfitidea点击:

Javascript For loop callback?

javascript

提问by wesbos

Trying to think in Javascript rather than jQuery, so I'm wondering if I'm doing this right.

试图用 Javascript 而不是 jQuery 来思考,所以我想知道我这样做是否正确。

I want to have a callback when my loop is finished. Is this the proper way?

我想在循环结束时进行回调。这是正确的方法吗?

for(var i = 0; i < divs.length; i++) {

  /* do some stuff */ 

  if ( i === (divs.length - 1)) {  /* call back */  }

}

I should add that I don't mean something like a JSON request callback, just when the loop has finished.

我应该补充一点,我的意思不是 JSON 请求回调之类的东西,只是在循环完成时。

回答by codelahoma

For clarity, you should go with @mu's answer, but if you really mustinclude the callback within the forconstruct, you can use the comma operator*:

为清楚起见,您应该使用@mu 的答案,但如果您确实必须for构造中包含回调,则可以使用逗号运算符*:

for(var i = 0;
    i < divs.length || function(){ /* call back */ }(), false;
    i++) {

/* do some stuff */ 

}

*As explained in this fascinating article.

*如这篇引人入胜的文章所述

回答by mu is too short

Why not say what you really mean and call the callback afterthe loop?

为什么不说出你真正的意思并在循环调用回调?

function thing_with_callback(divs, callback) {
    for(var i = 0; i < divs.length; i++) {
        /* do some stuff */ 
    }
    callback();
}

回答by hamzahik

Just to make codelahoma's answer simpler you can directly return false from your callback function. (to avoid re-executing the loop's code once more)

只是为了使 codelahoma 的答案更简单,您可以直接从回调函数中返回 false。(避免再次重新执行循环的代码)

for(var i = 0;i < divs.length || function(){ /* callback */ return false;}();i++){
/* loop code */
}

回答by user489419

It seems to me the question is about the execution order of javascript code. And the answers are:

在我看来,问题是关于 javascript 代码的执行顺序。答案是:

Yes you can put the callback outsidebecause javascript code is executed line by line. In case of asynchonous ajax calls there might be other things to consider.

是的,您可以将回调放在外面,因为 javascript 代码是逐行执行的。在异步 ajax 调用的情况下,可能还有其他事情需要考虑。