为什么计数器未在我的循环中重置?

时间:2019-04-24 14:58:05

标签: javascript arrays loops

我有一批货物,并且在阵列上运行一个循环以查找具有多个包裹的货物,因此我可以将它们克隆到一个新阵列中。我需要处理运输标签,该标签在阵列中每个对象上产生一个标签。

我添加了一个新的键/值对,以显示计数器中的单个包裹编号,但是我所有的“袋索引”都使用相同的编号

// Function to sort the concatenated array
    function compare( a, b ) {
  if ( a["SNAP ID"] < b["SNAP ID"] ){
    return -1;
  }
  if ( a["SNAP ID"] > b["SNAP ID"] ){
    return 1;
  }
  return 0;
}

// Demo shipments array
var shipments = [{
    "SNAP ID": "1234567890",
    "FULL NAME": "Person 1",
    "PACKAGE QTY": 5
    },
    {
        "SNAP ID": "0987654321",
        "FULL NAME": "Person 2",
        "PACKAGE QTY": 2
    },
    {
        "SNAP ID": "5432167890",
        "FULL NAME": "Person 3",
        "PACKAGE QTY": 3
    }
];

// Empty array which will contain cloned shipment objects
var data = [];

// Running loop on the shipments array
for (var i = 0; i < shipments.length; i++) {

        var Pkg = shipments[i]["PACKAGE QTY"]
        var shipment = shipments[i]
        shipment["BAG INDEX"] = 1

    // Running loop on the shipments containing more the 1 packages
    if (Pkg > 1) {

        for (var k = 0; k < (Pkg - 1); k++) {

            data.push(shipment);
            shipment["BAG INDEX"] += 1; 

            };
        };
    };

    var complete = shipments.concat(data);
    var sorted = complete.sort(compare);
    console.log(sorted);

这就是我要回来的

0: {SNAP ID: "0987654321", FULL NAME: "Person 2", PACKAGE QTY: 2, BAG INDEX: 2}
1: {SNAP ID: "0987654321", FULL NAME: "Person 2", PACKAGE QTY: 2, BAG INDEX: 2}
2: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
3: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
4: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
5: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
6: {SNAP ID: "1234567890", FULL NAME: "Person 1", PACKAGE QTY: 5, BAG INDEX: 5}
7: {SNAP ID: "5432167890", FULL NAME: "Person 3", PACKAGE QTY: 3, BAG INDEX: 3}
8: {SNAP ID: "5432167890", FULL NAME: "Person 3", PACKAGE QTY: 3, BAG INDEX: 3}
9: {SNAP ID: "5432167890", FULL NAME: "Person 3", PACKAGE QTY: 3, BAG INDEX: 3}
length: 10

2 个答案:

答案 0 :(得分:2)

您必须创建对象的副本。否则,您还将为已经添加到BAG INDEX数组中的对象增加data

只需使用:

data.push(Object.assign({}, shipment));

答案 1 :(得分:0)

您需要在此处创建一个新对象:

if (Pkg > 1) {
        for (var k = 0; k < (Pkg - 1); k++) {
            data.push(shipment);
            shipment["BAG INDEX"] += 1; 
          };
  };

否则,您只是在同一个装运对象上进行操作。