访问子函数中的循环迭代? [英] Accessing loop iteration in a sub-function?

查看:85
本文介绍了访问子函数中的循环迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Google Maps API在地图上绘制多个点。然而,在下面的点击事件函数中, i 始终设置为4,即它在迭代循环后的值:

I'm using the Google Maps API to plot several points on a map. However, in the click event function below, i is always set to 4, i.e. its value after iterating the loop:

// note these are actual addresses in the real page
var addresses = new Array( "addr 1", "addr 2", "addr 3", "addr 4" );

for (var i = 0; i < addresses.length; i++) {
    geocoder.getLatLng(addresses[i], function(point) {
        if (point) {
            var marker = new GMarker(point);
            map.addOverlay(marker);
            map.setCenter(point, 13);

            GEvent.addListener(marker, "click", function() {
                // here, i=4
                marker.openInfoWindowHtml("Address: <b>" + addresses[i] + "</b>");
            });
        }
    });
}

所以当标记显示它使用地址[4 ] ,这是未定义的。如何将 i 的正确值传递给函数?

So when the marker displays it's using addresses[4] which is undefined. How do I pass the correct value of i to the function?

推荐答案

您需要在当前迭代中生成匿名函数,以下内容应该解决:

You need to generate an anonymous function during the current iteration, the following should fix it:

// note these are actual addresses in the real page 
var addresses = new Array( "addr 1", "addr 2", "addr 3", "addr 4" ); 

for (var i = 0; i < addresses.length; i++) { 
    geocoder.getLatLng(addresses[i], function (current) { 
        return function(point) { 
            if (point) { 
                var marker = new GMarker(point); 
                map.addOverlay(marker); 
                map.setCenter(point, 13); 

                GEvent.addListener(marker, "click", function() { 
                    // here, i=4 
                    marker.openInfoWindowHtml("Address: <b>" + addresses[current] + "</b>"); 
                }); 
            }
        } 
    }(i)); 
} 

B //注意这些是真实页面中的实际地址
var addresses = new Array(addr 1,addr 2,addr 3,addr 4);

B// note these are actual addresses in the real page var addresses = new Array( "addr 1", "addr 2", "addr 3", "addr 4" );

for(var i = 0; i< addresses.length; i ++){
geocoder.getLatLng(addresses [i],function(point){
if(point){
var marker = new GMarker(point);
map.addOverlay(marker);
map.setCenter(point,13);

for (var i = 0; i < addresses.length; i++) { geocoder.getLatLng(addresses[i], function(point) { if (point) { var marker = new GMarker(point); map.addOverlay(marker); map.setCenter(point, 13);

        GEvent.addListener(marker, "click", function() { 
            // here, i=4 
            marker.openInfoWindowHtml("Address: <b>" + addresses[i] + "</b>"); 
        }); 
    } 
}); 

}



Google提供的 getLatLng 方法使用ajax调用获取特定地址的lat和long。由于这是一个异步调用,并且不是当前线程的一部分,因此需要一个回调函数,该函数在完成ajax请求时调用。这是您指定为函数的第二个参数的匿名函数。

现在,在进行ajax请求时,代码继续运行,增加 i 每次循环遍历数组。当你的第一个ajax调用返回时,循环已经增加到地址数组(4)的长度,所以当你的回调函数运行你正在检索范围内变量 i 之后循环增加。

Further Clarification
The getLatLng method provided by Google uses an ajax call to get the lat and long for a specific address. Since this is an asynchronous call and is not part of the current thread, a callback function is required which is called on completion of the ajax request. This is the anonymous function you specify as the second parameter of the function.
Now, whilst the ajax requests are being made, your code continues to run, increasing the value of i each time the loop iterates over the array. By the time your first ajax call returns, the loop has already increased to the length of the addresses array (4), so when the your callback function runs you're retrieving the in-scope variable i after it has been increased by the loop.

通过我写的修复,你创建了一个匿名函数,它接受一个参数 - current 返回上一个匿名函数,其中 i 变量替换为 current 变量。在循环的下一次迭代之前,使用 i 变量作为第一个参数,立即调用此函数。这将创建一个闭包,在调用函数时, i 的当前值存储在 current 变量中。当我们以后参考 current 变量时,我们得到 i 的存储值。

With the fix I wrote, you're creating an anonymous function that takes a single argument - current - and returns the previous anonymous function with the i variable replaced with the current variable. This function is invoked right away, before the next iteration of the loop, with the i variable as it's first parameter. This creates a closure for which the current value of i is stored in the current variable at the time the function is called. When we refer to the current variable later, we're getting the stored value of i.

我不是真的很好解释这些事情,可能是因为我对它的理解不如js神那么好。更好地阅读 javascript关闭的更多信息。

I'm not really very good at explaining these sort of things, probably because my understanding of it isn't quite as good as the js Gods. Better to read some more info on javascript closures.

这篇关于访问子函数中的循环迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆