我有语法问题,我正在尝试将go.pl分析集成到shopify中的购物车,因此最终代码将如下所示:
var goadservicesq = goadservicesq || [];
goadservicesq.push(
[
"_BASKET",
[
// first position in basket
{
identifier: '35353635535',
quantity: '2'
},
// second position in basket
{
identifier: '55353533378566',
quantity: '1'
},
// last position in basket
{
identifier: '458457435643464',
quantity: '3'
},
// extra product which solves the "comma" problem
{}
]
]
);

在这里,我正在尝试制作"因为"在里面循环以得到如上所述的最终结果:
// trying to make "for" loop
$.getJSON( "/cart.js", function( data ) {
console.log(data);
// user.go.pl CART script
var goadservicesq = goadservicesq || [];
goadservicesq.push(
[
"_BASKET",
[
for (var i = 0; i < data.items_count; i++) {
{
identifier: data.items[i].id,
quantity: data.items[i].quantity
},
}
// extra product which solves the "comma" problem
{}
]
]
);
});
&#13;
它会抛出错误 - &gt; http://prntscr.com/ci7jpz 请帮帮我。
答案 0 :(得分:3)
您需要在文字数组之外构建篮子数组:
// trying to make "for" loop
$.getJSON( "/cart.js", function( data ) {
console.log(data);
// user.go.pl CART script
var basket = [];
for (var i = 0; i < data.items_count; i++) {
basket.push({
identifier: data.items[i].id,
quantity: data.items[i].quantity
});
}
var goadservicesq = goadservicesq || [];
goadservicesq.push( [ "_BASKET", basket ] );
});
答案 1 :(得分:2)
你不能在这样的数组中创建一个循环,但如果data.items
是一个数组,你可以像这样使用Array.prototype.map:
$.getJSON( "/cart.js", function( data ) {
console.log(data);
// user.go.pl CART script
var goadservicesq = goadservicesq || [];
goadservicesq.push(
[
"_BASKET",
[
data.items.map(function (item) {
return {
identifier: item.id,
quantity: item.quantity
};
});
]
]
);
});