Javascript - 如何在带有回调的 for 循环中使用迭代器 [英] Javascript - how to work with the iterator in a for loop with callbacks

查看:29
本文介绍了Javascript - 如何在带有回调的 for 循环中使用迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 for 循环中访问回调函数使用的 i 的值.

I am trying in the for loop to access the value of the i with which the callback function uses.

我该怎么做?

for (var i = 0; i < a.length; i++)
{
    calcRoute(fixedLocation, my_cities[i].address, function(response) {

        // i want here to have the current "i" here

    });             
}

调用...

function calcRoute(x, y, callback) {

    var start = x;
    var end = y;

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        optimizeWaypoints: true
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            callback(response);                                                                 
        } else {
            alert("City unknown.")
        }       
    }); 
}

推荐答案

这是因为闭包捕获的是变量 i 本身,而不是当前值.试试:

It's because the closure captures the variable i itself, not the current value. Try:

for (var i = 0; i < a.length; i++) (function(i)
{
    calcRoute(fixedLocation, my_cities[i].address, function(response) {

        // i want here to have the current "i" here

    });             

}) (i);

这将为每次循环迭代创建一个新的 i 变量.

which will create a new i variable for each loop iteration.

这篇关于Javascript - 如何在带有回调的 for 循环中使用迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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