访问数组中的对象

时间:2013-07-30 14:08:27

标签: javascript jquery arrays object element

这里我有一个bigArray,其中有对象。每个对象都有top,left,lat,lng元素。

 bigArray  [Object, Object, Object, Object, Object, Object, Object, Object, Object]
    0: Object
    lat: 33.543
    leftPosition: 54
    lng: 56.345
    topPosition: -3
    __proto__: Object
    1: Object
    lat: 32.4534
    leftPosition: 197
    lng: 45.634345
    topPosition: 57
    __proto__: Object
    2: Object
    lat: 34.6434
    leftPosition: 245
    lng: -102.324234
    topPosition: -3
    __proto__: Object
    3: Object
    lat: 23.3423
    leftPosition: 330
    lng: 57.5343
    topPosition: 57
    __proto__: Object
    4: Object
    5: Object
    6: Object
    7: Object
   // N number of array etc... ...: Object
    length: 9
    __proto__: Array[0]

现在我有这个函数根据两个地方之间的lat和lng来计算km距离:

var loc1 = { lat: 42.672708, lon: 23.32147800000007 };
var loc2 = {lat:42.670242, lon:23.315002999999933};

function arc_distance(loc1, loc2) {
    var rad  = Math.PI / 180,
        earth_radius = 6371.009, // close enough
        lat1 = loc1.lat * rad,
        lat2 = loc2.lat * rad,
        dlon = Math.abs(loc1.lon - loc2.lon) * rad,
        M    = Math;

    return earth_radius * M.acos(
        (M.sin(lat1) * M.sin(lat2)) + (M.cos(lat1) * M.cos(lat2) * M.cos(dlon))
    );
}
alert (arc_distance(loc1,loc2));

但现在我有一个问题如何计算所有对象之间的距离?所以 object[0]---distance---object[1]---distance---object[2]---distance---object[N]bigArray

中有N个对象

所以我如何访问object[0].lat.lng , object[1].lat.lng , object[2].lat.lng并基于我的函数计算对象和距离之间的距离添加到对象,因此对象将为object{top,left,lat,lng, DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION}

2 个答案:

答案 0 :(得分:1)

这对你有用吗?

bigArray[0].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION=0;
for(var i=bigArray.length;i>0;i--){
   bigArray[i].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION=arc_distance(bigArray[i-1], bigArray[i]);
}

答案 1 :(得分:1)

试试这个

for (var i = arr.length-1; i > 0; i--) {
        arr[0].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION = 0; 
        arr[i].DISTANCE_FROM_PREVIOUS_OBJECT_LOCATION = arc_distance({lat: arr[i-1].lat, lon: arr[i-1].lng}, {lat: arr[i].lat, lon: arr[i].lng});
}

<强> JSFIDDLE