代码之家  ›  专栏  ›  技术社区  ›  codemon

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

  •  0
  • codemon  · 技术社区  · 6 年前

    我有一个简单的对象数组 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 回复  |  直到 6 年前
        1
  •  2
  •   Mohammed Ashfaq    6 年前

    // If this.length =3
    var arr = [
      {length: 3},
      {length: 3},
      {length: 3}
    ]
    
    arr.forEach((item, index)=> item.id =index)
    console.log(arr)
        2
  •  0
  •   user3568791    6 年前

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

    ];

        3
  •  0
  •   Jan Wendland    6 年前

    map 它将索引和数组分别作为第二个和第三个参数:

    const arr = [{title: 'A'}, {title: 'B'}, {title: 'C'}].map( (el, i, a) => ({id: i, ...el, length: a.length}));
    
    console.log(arr);
    
        4
  •  0
  •   Community paulsm4    4 年前

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

    创意:

    • MyList )它有一个数组来保存对象。
    • 创建另一个函数( MyTempObject )它只保存特定于对象的值。
    • 移动任何公共属性,比如 length 原型。
    • 我的列表 ,将数组设为私有,并创建一个公共属性,该属性返回此数组的副本。这将确保值是不可变的,并且只能使用公开的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)

    添加/删除