JavaScript多维数组不能作为数组访问,只能作为字符串访问

时间:2015-05-19 13:51:44

标签: javascript jquery arrays json google-maps

我想在Google地图上放置多个标记。我有JS构建一个数组并将其传递给处理标记的Google函数。 问题是,当我尝试访问假定的数组时,我只是得到第一个字符,好像它是一个字符串。

$(document).ready(function () {
    // initialize map to center on florida.
    initializeGMap();
    var locations = [];
    @foreach (var item in Model)
        {
            <text>        
            locations.push(@Html.Raw(Json.Encode("'" + item.Name + "'," + item.Location.Latitude + "," + item.Location.Longitude + "")));
            </text>
        }
    addMarker(locations);
});

我已经尝试了几种(读取:20+)这种变体,包括发送之前,发送之后的JSON.stringify等。这里也传递了它的功能:

function addMarker(locations) {

    var locations = JSON.stringify(locations);
    alert(locations + '\n' + locations[0][0] + '\n' + locations[0][1]);

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
    alert("done");
}

当它到达'locations [x] [x]'的行时,所有我都回到'['这是JSON字符串的第一个字符。它不是在阵列处理。 我错过了什么?

1 个答案:

答案 0 :(得分:0)

我通过以下方式解决了这个问题:

$(document).ready(function () {

    // initialize map to center on florida.
    initializeGMap();

    // serialize model locations
    var locationsToPass = @Html.Raw(Json.Encode(Model.Select(x => new { x.Name, x.Location.Latitude, x.Location.Longitude })));

    addMarker(locationsToPass);
});

并在接收函数中:

    function addMarker(locations) {
    var infowindow = new google.maps.InfoWindow();
    var marker, i;
    for (i = 0; i < locations.length; i++) {
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i].Latitude, locations[i].Longitude),
            map: map
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i].Name);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
}

故障排除的关键是使用它来检测我是否正在传递数组:

variable.constructor === Array

我得到了here