所以我尝试用五行填充数组“cat”,以保持每个类别在一个步骤中出现的次数的运行计数。问题是循环执行但它没有一个一个地输出结果所以我可以看到每个类别的计数如何上升的进程(时间序列)。它所做的一切就是吐出每个类别的总数
this.cat = [];
this.cat[0] = 0;
this.cat[1] = 0;
this.cat[2] = 0;
this.cat[3] = 0;
this.cat[4] = 0;
this.total = 0;
},
model: vote,
parse: function(data)
{
data = data.response ? data.response : data;
if(data.length == 0)
return;
for (var i = 0; i < data.length; i++) {
this.itemParse(data[i]);
};
return data;
},
itemParse: function(item){
this.cat[item.user_vote_index]++;
this.total++;
console.log(this.cat);
item.cat = this.cat;
item.total = this.total;
console.log(item);
return item;
}
})
})`
这是我做的时候的控制台日志
console.log(this.cat);
console.log(this.cat);
[1, 0, 0, 0, 0] stats.js:33
[1, 0, 0, 1, 0] stats.js:33
[1, 0, 1, 1, 0] stats.js:33
等到
[8, 6, 1, 2, 1]
这就是我希望存储数据的方式(一次迭代一次); 但是,当我控制台记录集合 item.cat 时,每一行都会给我 [8, 6, 1, 2, 1]
最佳答案
您必须修改您的itemParse
函数:
itemParse: function(item){
this.cat[item.user_vote_index]++;
this.total++;
// here you have to clone the array instead of creating a reference to it
item.cat = _.clone(this.cat);
item.total = this.total;
return item;
}
关于javascript - Backbone 模型循环输出最终对象而不是迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17281573/