将局部变量作为全局变量传递

时间:2014-09-08 12:28:52

标签: javascript

我正在使用Google Maps V3绘制一条线,我希望能够将局部变量loc作为全局传递,因此我可以在整个代码之外使用它。我怎么能这样做?

if(this.flightdetails.route_details.length > 0)
{
    $.each(this.flightdetails.posreports, function(i, nav)
    {
        var loc = new google.maps.LatLng(nav.latitude, nav.longitude);
        // Rest of code

        path[path.length] = loc;
        focus_bounds.extend(loc);
    });
}

3 个答案:

答案 0 :(得分:2)

var loc;
if(this.flightdetails.route_details.length > 0)
{
    $.each(this.flightdetails.posreports, function(i, nav)
    {
        loc = new google.maps.LatLng(nav.latitude, nav.longitude);
        // Rest of code

        path[path.length] = loc;
        focus_bounds.extend(loc);
    });
}
console.log(loc);

答案 1 :(得分:1)

定义您的变量global:

var loc; // global
if(this.flightdetails.route_details.length > 0)
{
    $.each(this.flightdetails.posreports, function(i, nav)
    {
        loc = new google.maps.LatLng(nav.latitude, nav.longitude); // with no var
        // Rest of code

        path[path.length] = loc;
        focus_bounds.extend(loc);
    });
}

答案 2 :(得分:0)

if(this.flightdetails.route_details.length > 0)
{
    $.each(this.flightdetails.posreports, function(i, nav)
    {
        this.loc = new google.maps.LatLng(nav.latitude, nav.longitude);
        // Rest of code

        path[path.length] = loc;
        focus_bounds.extend(loc);
    });
}