如何在 JavaScript 中获取对象的第一个、最后一个和其他值

how to get first,last and other values of object in javascript?

本文关键字:第一个 最后一个 其他 取对象 JavaScript 获取      更新时间:2023-09-26

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

[{"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中推送价值

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

// 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 循环允许您遍历数组中的所有航点:

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

您将以相同的方式访问中途停留属性:

waypts[j].stopover

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

因此,如果将该对象分配给变量

  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
 }

一个基本的例子:

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"
相关文章: