如何在Angular 2中检索数组的最后一个元素id

时间:2017-06-14 07:19:54

标签: javascript typescript

我正在尝试获取我的数组的最后一个元素的id。

这就是我获取数组最后一个元素的方法

let last = this.Array[this.Array.length-1];
console.log(last);

这是array-

的最后一个元素的控制台
Object {id: 48, title: "I'm used to this"}
 title: "I'm used to this"
 id:  48
__proto__:  Object

以下是我已经看过的清单 -

How to retrieve the clicked ElementId in angularjs?
How to get the object's id?
how to get the id name in html for any object还有更多,但我不能。

我只想访问id : 48,任何人都可以帮助我这样做 在此先感谢。

2 个答案:

答案 0 :(得分:5)

就这样做:

let last:any = this.Array[this.Array.length-1];
console.log(last.id);

答案 1 :(得分:4)

您可以执行this.Array.slice(-1)[0].id,而使用slice原始数组也不会更改。

DEMO:



var array = [{
  id: 43,
  title: "I'm used to this"
},{
  id: 44,
  title: "I'm used to this"
},{
  id: 45,
  title: "I'm used to this"
},{
  id: 46,
  title: "I'm used to this"
},{
  id: 47,
  title: "I'm used to this"
},{
  id: 48,
  title: "I'm used to this"
}]

console.log('last id : ' + this.array.slice(-1)[0].id)




<强>更新

由于您的数组项的类型为Object,因此首先将其转换为某种真实的class\interface类型,例如:

export  interface arrayItem{
    id?: number;
    title?: string;
}

然后定义您的数组类型,如:

你的数组

this.Array : Array<arrayItem> = [ {
  id: 48,
  title: "I'm used to this"
  },
  //your other array items
]