簡體   English   中英

定義 var 后“未捕獲的類型錯誤:無法讀取未定義的屬性‘長度’”

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

我目前正在加載一個 json 文件,然后解析它。 json 文件中的條目存儲為“地方”,我將其定義為全局變量,但瀏覽器仍然說它未定義。

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
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM