如何使对象在数组中找到自己的索引?

时间:2018-09-19 12:55:30

标签: javascript arrays

我有一个带有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
  }

]

但这不起作用。我是否必须使用数组外部的函数来执行此操作?内置方法没有帮助吗?

4 个答案:

答案 0 :(得分:2)

// If this.length =3
var arr = [
  {length: 3},
  {length: 3},
  {length: 3}
]

arr.forEach((item, index)=> item.id =index)
console.log(arr)

答案 1 :(得分:0)

每次推入数组时,您都可以获取当前数组长度并将其设置为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
 }

];

答案 2 :(得分:0)

您还可以使用map,它分别将索引和数组作为第二和第三参数:

const arr = [{title: 'A'}, {title: 'B'}, {title: 'C'}].map( (el, i, a) => ({id: i, ...el, length: a.length}));

console.log(arr);

答案 3 :(得分:0)

下面的答案试图解决如何使用类来创建上述结构,而不必循环以更改长度。

想法:

  • 创建一个函数(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)


一个原因,您可能希望在该数组中添加/删除条目的情况下使用此方法。您将不得不反复循环以更新每个对象的长度。