簡體   English   中英

如何在Angular 2中檢索數組的最后一個元素id

[英]How to retrieve last element id of array in Angular 2

我想獲取我的數組的最后一個元素的id。

這就是我獲取數組的最后一個元素的方法

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

這是數組的最后一個元素的控制台 -

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

這是我已經看過的清單 -

如何在angularjs中檢索單擊的ElementId?
如何獲取對象的id?
如何在html中獲取任何對象的id名稱以及更多但我不能。

我只是想訪問id : 48 ,任何人都可以幫我這樣做。
提前致謝。

就這樣做:

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

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

更新

由於你的Array項是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
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM