[英]JavaScript For Loop To Fill In Array
我有一個包含數組的 JavaScript 對象 (Shopify.checkout.line_items)。 我想用這些數據填充一個數組(項目)。
下面是代碼的簡化版本,核心問題是你不能在數組文字中間推一個 for 循環:
gtag('event', 'purchase', {
'transaction_id': '{{ order.order_number }}',
'items': [
for (var line_item_count = 0; line_item_count < Shopify.checkout.line_items.length; line_item_count++){
{ 'id':
'{{ item.variant_id }}',
'quantity': Shopify.checkout.line_items[line_item_count].quantity,
'price': Shopify.checkout.line_items[line_item_count].line_price
},
Shopify.checkout.line_items[line_item_count] += 1;
]
});
這是我希望實現的輸出:
gtag('event', 'purchase', {
'transaction_id': '123',
'items': [
{ 'id':
'53465346346',
'quantity': 2,
'price': 4
},
{ 'id':
'245643745764',
'quantity': 1,
'price': 1
}
]
});
如何使用正確的 JavaScript 循環填充數組文字?
您不能在數組文字中使用循環,但可以使用數組方法來實現某些結果:
gtag('event', 'purchase', {
'transaction_id': '{{ order.order_number }}',
'items': Array(Shopify.checkout.line_items.length).fill(0).map((_, line_item_count) => {
const result = {
'id': '{{ item.variant_id }}',
'quantity': Shopify.checkout.line_items[line_item_count].quantity,
'price': Shopify.checkout.line_items[line_item_count].line_price
};
Shopify.checkout.line_items[line_item_count] += 1;
return result;
})
});
Array(Shopify.checkout.line_items.length)
創建一個length
Shopify.checkout.line_items.length
的數組。 fill(0)
將每個元素設置為0
。 這一步是必要的,因為map
跳過所有未設置的元素。 map(...)
包含來自 for 循環的邏輯並返回一個新數組。
我不知道 Shopify 但如果Shopify.checkout.line_items
是一個數組或類似數組,您可以使用該數組而不是創建一個新數組並改進代碼:
gtag('event', 'purchase', {
'transaction_id': '{{ order.order_number }}',
'items': Shopify.checkout.line_items.map((el, idx, arr) => {
arr[idx]++;
return {
'id': '{{ item.variant_id }}',
'quantity': el.quantity,
'price': el.line_price
};
})
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.