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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44538051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:35:48  来源:igfitidea点击:

How to retrieve last element id of array in Angular 2

javascripttypescript

提问by S.Yadav

I am trying to get id of last element of my array.

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

This is how I am fetching last element of my array

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

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

Here is the console of last element of array-

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

Object {id: 48, title: "I'm used to this"}
 title: "I'm used to this"
 id:  48
__proto__:  Object

Here is the list on which I have looked already-

这是我已经看过的清单-

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 objectand many more but I could not.

如何在angularjs中检索点击的ElementId?
如何获取对象的id?
如何在 html 中获取任何对象的 id 名称等等,但我不能。

I just wanted to access id : 48, can any one help me to do so.
Thanks In Advance.

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

回答by Duannx

Just do that:

就这样做:

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

回答by anoop

You can do this.Array.slice(-1)[0].id, and with sliceyour original array is not changed too.

你可以做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)

Update:

更新

As your Array item is type of Object, So first convert it to some real class\interfacetype, Something like:

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

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

then define your array type, like :

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

your Array like

你的数组喜欢

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