我有这个代码
for (var i = 0; i < vm.items.users.data.length; i++) {
var user = vm.items.users.data[i];
user.goals_by_brands = [];
var brands = [];
vm.items.brands.data.forEach( function(element, index) {
brands.push(element);
});
console.log("brands", brands)
console.log("vm.items.brands.data", vm.items.brands.data)
brands.forEach( function(brand) {
brand.goals_by_months = [];
brand.user = user;
constants.MONTHS.forEach( function(month) {
brand.goals_by_months.push({goals: [], total_month_goal: 0, total_month_accumulated: 0});
});
user.goals_by_brands.push(brand);
});
}
我把这行:
var brands = [];
vm.items.brands.data.forEach( function(element, index) {
brands.push(element);
});
但是我也尝试了克隆数组(slice()函数),它也做同样的事情。
在brand数组和vm.items.brands.data数组中,出现的内容相同; vm.items.users.data数组中的最后一个用户。
我不知道为什么。
我想这样做:
我有用户群。 -> vm.items.users.data
我有很多品牌。 -> vm.items.brands.data
我有几个月的时间。 ->常量.MONTHS
我想为此对象添加数组-> {目标:[],total_month_goal:0,total_month_accumulated:0}至每个品牌12次(每月一次)。
然后这个品牌,我想添加到每个用户->
[
{
id: "user1",
name: "user1",
goals_by_brands: [
{
id: "brand1",
name: "brand1",
goals_by_months: [
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0},
{goals: [], total_month_goal: 0, total_month_accumulated: 0}
]
}
]
}]
因此,我想将用户添加到Goal_by_brands的每个品牌对象中。
对不起,我的英语。
最佳答案
因此,您代码的问题在于您拥有“品牌”引用,而不是品牌副本。由于您正在更改主要参考,因此品牌会不断改写,因此请在循环中进行更改。
var brands = [];
vm.items.brands.data.forEach( function(element, index) {
brands.push(element); //This pushes the reference which remains the same.
});
将此推送线更改为
var newBrand = JSON.parse(JSON.stringify(element))) //Make a deep copy of the element
brands.push(newBrand)
关于javascript - 在JavaScript中无法在其他内部使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42505542/