2017-04-19 51 views
0

问题:的JavaScript - 儿童元素,会同时使用一个for循环重复

我愿意得到一个子元素称为optionName(你可以看一下JSON数组下面有一个清晰的概念发生了什么),这需要我从一个嵌套的循环中获取它。到目前为止,我可以得到;但是,当我尝试将该子元素的值分配给变量(代码部分中的第5行)时出现问题,而我正在执行以下additions += i.optionName,这会使i.optionName的值被排序(一个接一个地排序,类似于数组),子元素得到积累,这使得下面出现:

Meal : Big Mac 
Options : 
Normal Ou Maxi ? : Maxi 
Choix du boisson : Fanta Orange 
Choix des frites : Frites steak house 
Category : Menus 
Qty : 1 
Price : 49 

Meal : Chicken McNuggets X6 
Options : 
//The first block is repeated again which is normal as I used additions +=** 
Normal OR Big ? : Big 
Choix du boisson : Fanta Orange 
Choix des frites : Steak house 

Normal OR Big ? : Normal 
Choix du boisson : Sprite 
Choix des frites : Steak house** 
Category : Menus 
Qty : 1 
Price : 45 

总之它变得尽可能的父元素更糟糕的还不止这些。你可能会说我为什么这么做,答案是因为在这个特殊情况下它需要是一个字符串,下面的变量dishes

当前的代码:

let dishes = ''; 
    let additions = ''; 

    var msg = MessageContent.orderedDishes.forEach(function(element) { 
     for(var i of element.selectedAdditions){ 
     additions += i.optionName + 
     ' : ' 
     + i.Name + '\n'; 
    } 

    dishes += 
     'Meal : ' + element.dishName + '\n' + 
     'Options : \n' + additions + '\n' + 
     'Category : ' + element.categoryName + '\n' + 
     'Qty : ' + element.qty+ '\n' + 
     'Price : ' + element.price + '\n\n'; 
}); 

这里是JSON数组我试图遍历:

[{ 
"objectId": "Kakao0MiRE", 
"price": 49, 
"dishName": "Big Mac", 
"categoryName": "Menus", 
"selectedAdditions": [{ 
    "optionName": "Normal Ou Big ?", 
    "Name": "Big", 
    "Price": 5 
}, { 
    "optionName": "Drink", 
    "Name": "Fanta Orange", 
    "Price": 0 
}, { 
    "optionName": "Fries", 
    "Name": "Steak house", 
    "Price": 0 
}], 
"additionalPrice": 5, 
"qty": 1 
}, { 
"objectId": "kOP90Ld8b9", 
"price": 45, 
"dishName": "Chicken McNuggets X6", 
"categoryName": "Menus", 
"selectedAdditions": [{ 
    "optionName": "Normal Ou Maxi ?", 
    "Name": "Normal", 
    "Price": 0 
}, { 
    "optionName": "Drink", 
    "Name": "Sprite", 
    "Price": 0 
}, { 
    "optionName": "Fries", 
    "Name": "Frites steak house", 
    "Price": 0 
}], 
"additionalPrice": 0, 
"qty": 1 }] 

回答

2

additions变量定义声明通话以外的forEach

当forEach迭代时,将值连接到现有的加法值,但从不将其重置为每个迭代的空字符串。这就是你的数据建立的原因。

可以,或者声明其forEach,使其与每个迭代空数组开始通过您的forEach回调的开始additions值设置为空字符串解决这个问题。我建议后者:

let dishes = ''; 

var msg = MessageContent.orderedDishes.forEach(function(element) { 
    // declaring your variable here ensures that 
    // it is empty at the beginning of the iteration 
    // rather than accumulating over all of them: 
    let additions = ''; 
    for(var i of element.selectedAdditions){ 
    additions += i.optionName + ' : ' + i.Name + '\n'; 
    } 
    dishes += 'Meal : ' + element.dishName + '\n' 
    + 'Options : \n' + additions + '\n' 
    + 'Category : ' + element.categoryName + '\n' 
    + 'Qty : ' + element.qty+ '\n' 
    + 'Price : ' + element.price + '\n\n'; 
}); 
+0

很棒!我不知道为什么我没看见它!谢谢! +1 –

+1

很高兴你发现这有帮助:) – Pineda