[英]How to make and object find its own index in an array?
我有一個帶有id
屬性的簡單對象數組,我需要id等於它們的索引。 我試過了
var arr = [
{
id: arr.indexOf(this),
length: this.length
},
{
id: arr.indexOf(this),
length: this.length
},
{
id: arr.indexOf(this),
length: this.length
}
]
但這是行不通的。 我是否必須使用數組外部的函數來執行此操作? 內置方法都無濟於事?
// If this.length =3 var arr = [ {length: 3}, {length: 3}, {length: 3} ] arr.forEach((item, index)=> item.id =index) console.log(arr)
每次推送到數組時,您都可以獲取當前數組長度並將其設置為id:
var array = [];
array.push({id: array.length});
您也可以使用循環:
var array = [];
for(var i = 0; i < howeveryouwant; i++){
array[i] = {id: i};
}
如果初始化是靜態的,則可以設置id:
var arr = [
{
id:0,
length: this.length
},
{
id: 1,
length: this.length //this will be 0
},
{
id: 2,
length: this.length //this also will be 0
}
];
您也可以使用map
,它分別將index和array作為第二和第三參數:
const arr = [{title: 'A'}, {title: 'B'}, {title: 'C'}].map( (el, i, a) => ({id: i, ...el, length: a.length}));
console.log(arr);
以下答案試圖解決如何使用類來創建上述結構,而不必循環更改長度。
MyList
),該函數具有一個包含對象的數組。 MyTempObject
),該函數僅保存特定於對象的值。 length
更改為原型。 MyList
,將數組設為私有,並創建一個公共屬性,該屬性返回此數組的副本。 這將確保該值是不可變的,並且只能使用公開的API進行突變。 function MyList () { var values = []; function MyListItem(id) { this.id = id; } Object.defineProperty(MyListItem.prototype, 'length', { get: function() { return values.length; } }); Object.defineProperty(this, 'value', { get: function() { return values.slice(); } }); this.add = function(id) { values.push(new MyListItem(id)); } } var myList = new MyList(); myList.add(1); console.log(myList.value) console.log(myList.value[0].length) myList.add(2); console.log(myList.value) console.log(myList.value[0].length) myList.add(3); console.log(myList.value) console.log(myList.value[0].length)
一個原因,您可能希望使用此方法,是在此數組中添加/刪除條目的情況下。 您將不得不反復循環以更新每個對象的長度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.