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

S.Y*_*dav 4 javascript typescript

我想获取我的数组的最后一个元素的id.

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

let last = this.Array[this.Array.length-1];
console.log(last);
Run Code Online (Sandbox Code Playgroud)

这是数组的最后一个元素的控制台 -

Object {id: 48, title: "I'm used to this"}
 title: "I'm used to this"
 id:  48
__proto__:  Object
Run Code Online (Sandbox Code Playgroud)

这是我已经看过的清单 -

如何在angularjs中检索单击的ElementId?
如何获取对象的id?
如何在html中获取任何对象的id名称以及更多但我不能.

我只想访问id : 48,任何人都可以帮助我这样做.
提前致谢.

ano*_*oop 5

你可以做this.Array.slice(-1)[0].id,并且slice你的原始数组也没有改变。

演示:

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)
Run Code Online (Sandbox Code Playgroud)

更新

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

export  interface arrayItem{
    id?: number;
    title?: string;
}
Run Code Online (Sandbox Code Playgroud)

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

你的数组喜欢

this.Array : Array<arrayItem> = [ {
  id: 48,
  title: "I'm used to this"
  },
  //your other array items
]
Run Code Online (Sandbox Code Playgroud)


Dua*_*nnx 5

就这样做:

let last:any = this.Array[this.Array.length-1];
console.log(last.id);
Run Code Online (Sandbox Code Playgroud)