我不明白为什么下面的行失败。无法将对象推入数组,javascript
locations.push(location);
我想创建充满位置对象(注释,经度,纬度)的阵列(位置)。注释也是一个数组,但充满了注释对象(ID,智能区,时间戳,条目,操作)。
以下是代码片段。
var map;
var locations = [];
function Location() {
this.annotations = []; /* Array of annotations */
this.latitude = null; /* Location latitude */
this.longitude = null; /* Location longitude */
}
function Annotation() {
this.ID = null;
this.smartzone = null;
this.timestamp = null;
this.entry = null;
this.action = null;
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(42.73, -84.49),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$.getJSON("http://www.site.com/pathto/map/json.php", function(data) {
$.each(data, function(key, val) {
//alert(val.ID);
var location = new Location();
var annotation = new Annotation();
if (locations.length === 0) {
annotation.ID = val.ID;
annotation.smartzone = val.smartzone;
annotation.timestamp = val.timestamp;
annotation.entry = val.entry;
annotation.action = val.action;
location.annotations.push(annotation);
location.latitide = val.latitude;
location.longitude = val.longitude;
locations.push(location); /* This is the line that fails */
} else {
var locationExists = false;
for (var i = 0; i < annotations.length; i++) {
if (val.latitude == locations[i].latitude && val.longitude == locations[i].longitude) {
locationExists = true;
}
}
if (locationExists) {
annotation.ID = val.ID;
annotation.smartzone = val.smartzone;
annotation.timestamp = val.timestamp;
annotation.entry = val.entry;
annotation.action = val.action;
locations[i].annotations.push(annotation);
} else {
annotation.ID = val.ID;
annotation.smartzone = val.smartzone;
annotation.timestamp = val.timestamp;
annotation.entry = val.entry;
annotation.action = val.action;
location.annotations.push(annotation);
location.latitide = val.latitude;
location.longitude = val.longitude;
//locations.push(location); /* Same problem */
}
}
});
});
}
你收到了什么错误? –
你的意思是“失败”?失败如何? –