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

对象数组Javascript中的增量ID

  •  0
  • MrX  · 技术社区  · 4 年前

    我有一个数组对象和一个数组,如下所示:

    let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
    let selected = [];
    

    我实现了点击进入 data 数据 selected . 在其ID为的索引中,没有 挑选出来的

    1

      const dataObject = {"name": "Apple"};
      dataObject['position'] = selected.length;
      selected.push(dataObject);      
    
      const dataObject = {"name": "Apple"};
      selected.push(dataObject);
      for(let i = 0; i<selected.length; i++) {
        selected[i]['position'] = i;
      }
    

    奇怪的是如果有相同的物体 Apple, Orange, Apple ,我在数组中得到了错误的ID,比如:

    [{"name": "Apple", position: 2} , {"name": "Orange", position: 1}, {"name": "Apple", position: 2}]
    

    #编辑:

    这里是可复制代码:

    let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
    let selected = [];
    
    const dataObject = {"name": "Apple"};
    selected.push(dataObject);
    selected.push(dataObject);
    for(let i = 0; i<selected.length; i++) {
      selected[i]['position'] = i;
    }
    
    document.write('<br>' + JSON.stringify(selected));
    
    // Output : [{"name":"Apple","position":1},{"name":"Apple","position":1}] 
    // Output Expect: [{"name":"Apple","position":0},{"name":"Apple","position":1}] 
    

    我不知道是什么错,任何建议都会对我有帮助。提前感谢

    1 回复  |  直到 4 年前
        1
  •  0
  •   kewlashu    4 年前

    dataObject 在中通过引用分配 selected 数组,所以它的同一个对象被你分配两次,一次改变将改变 挑选出来的 数组,因为它们是同一个对象。

    let data = [{"name": "Apple"} , {"name": "Orange"}, {"name": "Pineapple"}]
    let selected = [];
    
    const dataObject = {"name": "Apple"};
    
    //assigning a new object to selected by using dataObject
    selected.push({"name":dataObject.name});
    
    //assigning a new object to selected by using dataObject
    selected.push({"name":dataObject.name});
    
    for(let i = 0; i<selected.length; i++) {
      selected[i]['position'] = i;
    }
    
    document.write('<br>' + JSON.stringify(selected));

    答案 this question 可以让你开始学习更多