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

查看:108
本文介绍了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天全站免登陆