在子函数中访问循环迭代?

发布于 2024-08-18 05:52:01 字数 780 浏览 5 评论 0原文

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

// 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>");
            });
        }
    });
}

因此,当标记显示时,它使用addresses[4],其中未定义。如何将 i 的正确值传递给函数?

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>");
            });
        }
    });
}

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眉黛浅 2024-08-25 05:52:01

您需要在当前迭代期间生成一个匿名函数,以下应该修复它:

// 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 地址 = new Array( "addr 1", "addr 2", "addr 3", "addr 4" );

for (var i = 0; i < 地址.length; i++) {
geocoder.getLatLng(地址[i], 函数(点) {
如果(点){
var 标记 = new GMarker(point);
map.addOverlay(标记);
地图.setCenter(点, 13);

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

}

进一步说明
Google 提供的 getLatLng 方法使用 ajax 调用来获取特定地址的纬度和经度。由于这是一个异步调用并且不是当前线程的一部分,因此需要一个回调函数,该函数在 ajax 请求完成时调用。这是您指定为函数第二个参数的匿名函数。
现在,在发出 ajax 请求的同时,您的代码将继续运行,每次循环遍历数组时都会增加 i 的值。当您的第一个 ajax 调用返回时,循环已经增加到地址数组的长度 (4),因此当您的回调函数运行时,您将在之后检索范围内变量 i它已通过循环增加。

通过我编写的修复,您将创建一个匿名函数,该函数采用单个参数 - current - 并返回前一个匿名函数,并将 i 变量替换为 >当前变量。在下一次循环迭代之前,立即调用此函数,并使用 i 变量作为第一个参数。这将创建一个闭包,在调用函数时,i 的当前值存储在 current 变量中。当我们稍后引用 current 变量时,我们将获取 i 的存储值。

我不太擅长解释这类事情,可能是因为我对它的理解不如js大神。最好阅读有关 javascript 闭包的更多信息

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// 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>"); 
        }); 
    } 
}); 

}

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.

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.

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.

放手` 2024-08-25 05:52:01

我不应该在该循环中达到 4。只要 i < < ,循环就会运行。地址.长度(即 4),因此循环应从 i=0 运行到 i=3。

i should not reach 4 in that loop. The loop runs so long as i < addresses.length (which is 4), so the loop should run from i=0 to i=3.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文