1

我有一个像这样的对象,其中包含位置和中途停留值。

[{"location":"8, Nehru Nagar, Ambavadi, Ahmedabad, Gujarat 380015, India","stopover":true},
{"location":"CISF Cargo Road, Sardar Vallabhbhai Patel International Airport (AMD), Hansol, Ahmedabad, Gujarat 382475, India","stopover":true},
{"location":"Sardar Patel Ring Road, Sughad, Ahmedabad, Gujarat 382424, India","stopover":true},
{"location":"Kudasan Road, Urjanagar 1, Kudasan, Gujarat 382421, India","stopover":true},
{"location":"Gujarat State HIghway 141, Alampur, Gujarat 382355, India","stopover":true},
{"location":"Hanuman Ji Mandir Bus Stop, Dabhoda, Gujarat 382355, India","stopover":true}]

所以我的问题是
(1)如何将位置的第一个值作为起始目的地?
(2)如何将位置的最后一个值作为最终目的地?
(3) 如何获取其他位置值作为航点?

看到这个,我是如何在 waypts 中推值的

4

3 回答 3

1

这不仅仅是一个对象,它是一个数组,因此可以通过索引访问项目。

因此,如果该对象被分配给一个变量

  places = [{"location":"8, Nehru Nagar, Ambavadi, Ahmedabad, Gujarat 380015, India","stopover":true},
{"location":"CISF Cargo Road, Sardar Vallabhbhai Patel International Airport (AMD), Hansol, Ahmedabad, Gujarat 382475, India","stopover":true},
{"location":"Sardar Patel Ring Road, Sughad, Ahmedabad, Gujarat 382424, India","stopover":true},
{"location":"Kudasan Road, Urjanagar 1, Kudasan, Gujarat 382421, India","stopover":true},
{"location":"Gujarat State HIghway 141, Alampur, Gujarat 382355, India","stopover":true},
{"location":"Hanuman Ji Mandir Bus Stop, Dabhoda, Gujarat 382355, India","stopover":true}];

您可以访问

 places[0]; // first
 places[places.length -1]; // last

并迭代使用

 for ( var i = 1; i < places.length - 2 ; i++){
    places[i]; // access to waypoints
 }
于 2013-10-16T05:51:07.397 回答
1

一个基本的例子:

var a = [{p:1},{p:2},{p:3},{p:4}];
/* first */  a[0];            // Object {p: 1}
/* last */   a[a.length - 1]; // Object {p: 4}
/* second */ a[1];            // Object {p: 2}
             a[0].p;          // 1

不要依赖typeof

typeof new Array // "object"
typeof new Object // "object"
于 2013-10-16T05:53:02.187 回答
1

你有一个对象数组。可以通过数字索引访问数组中的各个项目,然后可以通过名称访问每个对象的各个属性。所以:

// assuming waypts is the variable/function
// argument referring to the array:

var firstLoc = waypts[0].location;
var lastLoc = waypts[waypts.length-1].location;

请记住,JS 数组索引从 0 开始,您可以使用

waypts[n].location

当然,标准 for 循环允许您遍历数组中的所有航点:

for(var j=0; j < waypts.length; j++) {
    alert(waypts[j].location);
}

您将以相同的方式访问stopover属性:

waypts[j].stopover
于 2013-10-16T06:00:35.730 回答