我正在尝试使用 GTM 自定义 JS 来汇总数组中的产品价格。数组元素是可变的。我的数据源变量如下所示:
dl_products_checkout = [ { name: 'Sports Gel SPF 20', id: '1125200001', price: '23.9', brand: 'ultrasun', quantity: 1 }, { name: 'Almost Powder Makeup SPF 15 9 g Neutral', id: '1081040004', price: '25.9', brand: 'Clinique', quantity: 1 } ]
不幸的是,我得到 NaN 作为返回值。到目前为止,这是我的解决方案:
function() {
var items = {{dl_products_checkout}};
var ids = [];
var totalValue = 0;
var i, len;
for (i = 0, len = items.length; i < len; i++) {
totalValue += parseInt(items[i].price);
}
return ids.push(totalValue);
}
如果有人能告诉我我在这里做错了什么,那就太好了。非常感谢!
最诚挚的问候, 安东
最佳答案
首先,我认为您返回了错误的值......
试试这个:
/***
We create a function, we might want to use it more then once.
***/
function CalculateTotal( items ) {
// First we check if we have something to work with.
if ( items.length < 1 || items === undefined ) {
return null;
} else { // We can do stuff
var total_value = 0; // we need something to store the total value in.
for ( var i = 0; i < items.length; i ++ ) { // Let's go through the list.
total_value += items[i].price; // add the price to total
console.log( "total_value = " + total_value ); // check total value
console.log( items[i].name + " = " + items[i].price ); // check item price
}
// now we are all done
return total_value;
}
并使用类似:
var total = CalculateTotal( dl_products_checkout );
关于javascript - 对数组中的字符串值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40085653/