Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
非常奇怪的Javascript范围问题_Javascript_Variables_Scope - Fatal编程技术网

非常奇怪的Javascript范围问题

非常奇怪的Javascript范围问题,javascript,variables,scope,Javascript,Variables,Scope,以下变量my_cords在进入谷歌地图功能时未定义,有人能理解为什么并可能给我一个解决方法吗?我已经在顶部定义了它,并将其设置在回调函数中,我以前见过它在全局变量上的工作 $(document).ready(function () { var my_cords; var map; function getCareHome() { geocoder = new google.maps.Geocoder(); //var address = document.getEleme

以下变量my_cords在进入谷歌地图功能时未定义,有人能理解为什么并可能给我一个解决方法吗?我已经在顶部定义了它,并将其设置在回调函数中,我以前见过它在全局变量上的工作

$(document).ready(function () {

var my_cords;
var map;

function getCareHome() {

    geocoder = new google.maps.Geocoder();

    //var address = document.getElementById("address").value;

    var address = "address here";

    geocoder.geocode( { 'address': address}, function(results, status) {

        if (status == google.maps.GeocoderStatus.OK) {

            my_cords = results[0].geometry.location;

        } else {

            alert("Sorry we couldn't locate the carehome on the map: " + status);
            return false;

        }

    });



    var myOptions = {
        zoom: 7,
        center: my_cords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

}

getCareHome();

});

.geocode
是一个异步调用

尝试在函数中使用回调

例如:

geocoder.geocode( { 'address': address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK) {

        createMap(results[0].geometry.location);

    } else {

        alert("Sorry we couldn't locate the carehome on the map: " + status);
        return false;

    }

});

var createMap = function(my_cords)  {
     var myOptions = {
        zoom: 7,
        center: my_cords,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

geocoder.geocode是一个异步函数。设置
my_cords
的匿名函数在触发某个事件(可能是HTTP响应的到达)之前不会运行


将依赖于其运行的代码移到该函数内部。

因为
geocode
是异步运行的,所以您的代码将在以后使用
my\u cords
(设置
myOptions
)在从
geocode
运行完成回调之前,将看到
my\u cords
的值,因此
myOptions.center
将是
未定义的


如果您在设置
myOptions
时需要
my_跳线
,则必须将该代码移动到
geocode
上的回调中。不建议使用
var createMap=function…
表单。除此之外,+1。@Neal:
function createMap
我会使用函数声明,就像OP在
getCareHome
中使用的那样,而不是函数表达式。@T.J.Crowder为什么我的方式会有所不同?我只是在演示如何创建函数。我没有注意函数的OPs声明。@Neal:它发生在不同的时间,并导致一个变量引用匿名函数。函数声明发生在作用域中执行任何分步代码之前,并导致绑定和具有适当名称的函数。更多:@Neal你让这听起来很容易!谢谢你的快速回复。学到了一些新的东西。干杯,刚刚到达终点,不过我提高了你的答案!