简体   繁体   中英

Fill Array in Javascript

How to Fill this type of Array in Javascript..

var neighborhoods = [
    {lat: 52.511, lng: 13.447},
    {lat: 52.549, lng: 13.422},
    {lat: 52.497, lng: 13.396},
    {lat: 52.517, lng: 13.394}
];

I have tried this way but its not happening

$.each(result.geoloc, function(index,geoloc) {
    geoloc_split=geoloc.Geoloc.split(',');
    // alert(geoloc_split[0]+","+geoloc_split[1]);
    var lat="lat: "+geoloc_split[0];
    var lng = "lng: "+geoloc_split[1];
    neighborhoods.push(lat,lng);
    geoloc_split="";
});

You are pushing only values to array. You need to push new object (eg create it with object literal). Furthermore you need to convert string values to float:

var lat = parseFloat(geoloc_split[0]);
var lng = parseFloat(geoloc_split[1]);
neighborhoods.push({
    lat: lat,
    lng: lng
});

In ES6 you can use property value shorthand:

neighborhoods.push({lat, lng});

You should do like this :

$.each(result.geoloc, function(index,geoloc) {
     geoloc_split=geoloc.Geoloc.split(',');

     neighborhoods.push({
         lat:parseFloat(geoloc_split[0]),
         lng:parseFloat(geoloc_split[1])
     });

     geoloc_split="";
});

Because your neighborhood array is an array of object you need to fill it with objects .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM