JavaScript For循环填充数组



我有一个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)创建一个包含lengthShopify.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
};
})
});

最新更新