"未捕获的类型错误:无法读取属性'长度'未定义的“;在定义变量之后

"Uncaught TypeError: Cannot read property 'length' of undefined" after defining var

本文关键字:未定义 长度 之后 变量 定义 属性 quot 类型 错误 读取      更新时间:2023-09-26

我目前正在加载一个json文件,然后对其进行解析。json文件中的条目存储为"place",我将其定义为全局变量,但浏览器仍然表示它未定义。

var request;
var places;
var map;
var myLatLng = {lat: 34, lng: 38};
// load database and parse into entries
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'places.json');
request.onreadystatechange = function() {
    if ((request.readyState ===4) && (request.status===200)) {
        places = JSON.parse(request.responseText);
    }
}
request.send();
function initMap() {
    var mapOptions = {
        zoom: 6,
        center: myLatLng,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    // initialize the map
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    for (var i = 0; i < places.length; i++) {
        // the place
        var place = places[i];
        // place co-ordinates
        var latlng = new google.maps.LatLng(place.latitude, place.longitude);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map, 
            title: place.city
        });
    }
}

Jonathan Lonowski和Shashank提供的评论是您面临问题的最可能原因。您需要确保在AJAX调用完成后调用initMap。因此,您可以将onreadystatechanged方法修改为以下内容:

request.onreadystatechange = function() {
    if ((request.readyState ===4) && (request.status===200)) {
        places = JSON.parse(request.responseText);
        initMap();
    }

然而,我也想用Javascript的说法来澄清undefined的概念。

在Javascript中,当一个变量被声明(但没有赋值)时,它被设置为值undefined。注意,undefined而不是null相同,后者更像是一个赋值。

这个答案将澄清undefinednull之间的混淆。然后,您将能够理解为什么浏览器将变量位置显示为undefined

根据OP的注释进行编辑如果您从HTML文件中调用该方法,仍然有一种方法可以使页面正常运行,但延迟可以忽略不计。

参考我在下面提出的替代解决方案

var request;
var places;
var map;
var myLatLng = {lat: 34, lng: 38};
// load database and parse into entries
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'places.json');
request.onreadystatechange = function() {
    if ((request.readyState ===4) && (request.status===200)) {
        places = JSON.parse(request.responseText);
        //now that the places array has been initialized you can call
        //placeMarkers() to place markers on the map.
        placeMarkers();
    }
}
request.send();
//initMap can be safely invoked within the HTML page using window.onload.
//this only initializes the map instance and sets it to a valid reference.
//there are *no* place markers added yet
function initMap() {
    var mapOptions = {
        zoom: 6,
        center: myLatLng,
        mapTypeControl: true,
        mapTypeControlOptions: {
            style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
            position: google.maps.ControlPosition.TOP_RIGHT
        },
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    // initialize the map. Here map should be the global variable and not a new declaration
    map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function placeMarkers(){
    for (var i = 0; i < places.length; i++) {
        // the place
        var place = places[i];
        // place co-ordinates
        var latlng = new google.maps.LatLng(place.latitude, place.longitude);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map, 
            title: place.city
        });
    }
}