且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何确保将正确的参数传递给循环中声明的函数调用?

更新时间:2023-09-06 18:19:46

这里的直接问题是 j 关键字变量继续改变之前调用回调。

The immediate problem here is that the j and keyword variables go on changing before the callbacks are called.

一个简单的解决方案是在闭包中保护这个变量:

A simple solution is to protect this variable in a closure :

for (var j=0; j<keywords.length; j++) {
    (function(j){
        var keyword = keywords[j];
        ...
    })(j);
}

当你刚刚使用一个简单的数组时,你也可以使用通过 forEach $关闭c $ c>

When you're just working with a simple array, then you can also use a closure through forEach :

keywords.forEach(function(keyword, j){
     ...
});

要处理这种异步问题,你现在应该深入了解有助于构建代码的promises更清晰(更少缩进)的方式。 简介

To deal with this kind of asynchronous problems, you should now dive in promises which help structure your code in a clearer (and less indented) way. An introduction.