我有一个像这样的对象,它包含位置和中途停留值。
[{"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)如何获得其他位置值作为航路点?
答案 0 :(得分: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
}
答案 1 :(得分: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"
答案 2 :(得分: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开始,您可以使用
获取数组中位置 n 的位置waypts[n].location
当然,循环标准允许您遍历数组中的所有航路点:
for(var j=0; j < waypts.length; j++) {
alert(waypts[j].location);
}
您可以通过相同的方式访问中途停留属性:
waypts[j].stopover