問題:的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 }]
很棒!我不知道爲什麼我沒看見它!謝謝! +1 –
很高興你發現這有幫助:) – Pineda