[英]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.