数组推入for循环在Object容器中具有不同的值

时间:2016-05-14 17:13:54

标签: javascript arrays object

我是编程的新手,只是想知道为什么输出newContainer与我在forloop中推送的不同。检查console.log以获取详细信息。

ng-repeat

我试图得到如下的输出。谢谢!

var data = [{
    Fruit: "Apple",
    Count: "1",
    Date: "2014"
}, {
    Fruit: "Banana",
    Count: "1",
    Date: "2015"
}, {
    Fruit: "Carrot",
    Count: "1",
    Date: "2014"
}, {
    Fruit: "Orange",
    Count: "1",
    Date: "2016"
}, {
    Fruit: "Apple",
    Count: "1",
    Date: "2012"
}, {
    Fruit: "Banana",
    Count: "1",
    Date: "2011"
}, {
    Fruit: "Apple",
    Count: "1",
    Date: "2010"
}];



var lineItemCount = new Array(5).fill(0);
var lineItems = ["Apple", "Banana", "Carrot", "Orange"];
var newContainer = [];

for (var i = 0; i < data.length; i++) {

    var checkItem = lineItems.indexOf(data[i].Fruit); //get index of item in lineItems

    lineItemCount[checkItem] = lineItemCount[checkItem] + 1;
    lineItemCount[0] = data[i].Date;

    newContainer.push(lineItemCount);
    console.log(lineItemCount);

};
console.log(newContainer);

3 个答案:

答案 0 :(得分:0)

您的元素是通过引用推送的。只需复制然后推送即可。

例如,将newContainer.push(lineItemCount);更改为newContainer.push(Array.from(lineItemCount));

答案 1 :(得分:0)

主要问题是你反复推送同一个数组到结果。虽然在 push 时,数组的值与下一个 push 不同,但数组是引用,因此当数组内的值递增时,对该数组的引用将看到这个,甚至是那些已经推送过的引用。

这是更正后的代码,它使用slice(0)将数组元素复制到一个新数组中然后被推送:

// 5 elements, first one for date
var lineItemCount = new Array(5).fill(0);

var lineItems = [null, "Apple", "Banana", "Carrot", "Orange"];
var newContainer = [];

for (var i = 0; i < data.length; i++) {

    var checkItem = lineItems.indexOf(data[i].Fruit); //get index of item in lineItems

    lineItemCount[checkItem] = lineItemCount[checkItem] + 1;
    lineItemCount[0] = data[i].Date;

    newContainer.push(lineItemCount.slice(0)); // take array copy
    console.log(lineItemCount);

};
console.log(newContainer);

还请注意数组中带有水果名称的附加项。这样可以确保不会在为日期保留的索引0处增加元素。

答案 2 :(得分:0)

您可以使用som助手,一个用于直接访问fruit数组位置的索引,另一个用于容器中已插入数组的哈希表。

其余的是检查日期数组是否已经存在,如果没有,则构建一个空值和前面的日期。然后将其推送到container

现在将计数添加到适当的日期和列。

var data = [{ Fruit: "Apple", Count: "1", Date: "2014" }, { Fruit: "Banana", Count: "1", Date: "2015" }, { Fruit: "Carrot", Count: "1", Date: "2014" }, { Fruit: "Orange", Count: "1", Date: "2016" }, { Fruit: "Apple", Count: "1", Date: "2012" }, { Fruit: "Banana", Count: "1", Date: "2011" }, { Fruit: "Apple", Count: "1", Date: "2010" }],
    lineItems = ["Apple", "Banana", "Carrot", "Orange"],
    container = [],
    items = {};

lineItems.forEach(function (a, i) { items[a] = i; });

data.forEach(function (a) {
    if (!this[a.Date]) {
        this[a.Date] = [a.Date].concat(lineItems.map(function () { return 0; }))
        container.push(this[a.Date]);
    }
    this[a.Date][items[a.Fruit] + 1] += +a.Count;
}, Object.create(null));

document.write('<pre>' + JSON.stringify(container, 0, 4) + '</pre>');