我从 php 文件生成一些 javascript。在这个生成的代码中,我创建了一个多维数组,然后填充它。第一个嵌套数组填充没有问题,但第二个嵌套数组抛出 TypeError: myArray[idx] is undefined。
这是一个代码片段:
function initialize() {
var arrayLabels = [];
var arrayMarkers = [];
var idx = 0;
arrayMarkers[idx] = [];
var mapLatlng = new google.maps.LatLng(40.6029248937, 7.7861327300);
var mapOptions = { center: mapLatlng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.SATELLITE };
var map = new google.maps.Map(document.getElementById("karte"), mapOptions);
var bounds = new google.maps.LatLngBounds();
arrayMarkers[idx]['breite'] = 44.4114053473682;
arrayMarkers[idx]['laenge'] = 8.91858100891113;
arrayMarkers[idx]['farbe'] = "http://new.kfb.localhost:8888/img/ico/button2_gruen.png";
arrayMarkers[idx]['hafen'] = "Ab/bis Genua";
arrayMarkers[idx]['link'] = "Karte, Wetter und<br>Landausflüge für<br><a href='hafen.php?hafen=172'>Genua</a><br>Sa, 16.03.13";
idx++;
arrayMarkers[idx]['breite'] = 43.3449053146323;
错误在最后一行抛出,就在索引递增之后。知道问题出在哪里吗?
谢谢 马克
最佳答案
你递增 idx
,然后这样做:
arrayMarkers[idx]['breite'] = 43.3449053146323;
您从未在 arrayMarkers[idx]
中放置任何对象,因此您最终尝试向 undefined
添加属性,这会导致错误。
如果要在新索引处创建数组,请添加此处显示的第二行:
idx++;
arrayMarkers[idx] = []; // <=== Add this
arrayMarkers[idx]['breite'] = 43.3449053146323;
旁注:您放入 arrayMarkers[idx]
的内容是数组 ([]
),但您并未将它们用作数组,您将它们用作对象。您可以在 JavaScript 中执行此操作(因为那些数组 aren't really arrays at all ),但除非您要利用它们是数组这一事实,否则我只使用对象:
arrayMarkers[idx] = {}; // Instead of []
关于Javascript 数组数组 -> array[index] 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14975869/