首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在javascript中获得对象的第一、最后和其他值?

如何在javascript中获得对象的第一、最后和其他值?
EN

Stack Overflow用户
提问于 2013-10-16 05:48:23
回答 3查看 83关注 0票数 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)如何获得其他位置值作为路径点?

see this,how i pushed value in waypts

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-10-16 06:00:35

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

代码语言:javascript
复制
// 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开始,您可以使用

代码语言:javascript
复制
waypts[n].location

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

代码语言:javascript
复制
for(var j=0; j < waypts.length; j++) {
    alert(waypts[j].location);
}

您可以以同样的方式访问“中途停留”属性:

代码语言:javascript
复制
waypts[j].stopover
票数 1
EN

Stack Overflow用户

发布于 2013-10-16 05:51:07

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

因此,如果将该对象赋值给变量

代码语言:javascript
复制
  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}];

你可以访问

代码语言:javascript
复制
 places[0]; // first
 places[places.length -1]; // last

和迭代使用

代码语言:javascript
复制
 for ( var i = 1; i < places.length - 2 ; i++){
    places[i]; // access to waypoints
 }
票数 1
EN

Stack Overflow用户

发布于 2013-10-16 05:53:02

一个基本的例子:

代码语言:javascript
复制
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

代码语言:javascript
复制
typeof new Array // "object"
typeof new Object // "object"
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19396099

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档