汇总数组

时间:2016-10-17 11:50:18

标签: javascript arrays google-tag-manager

我试图用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);
}

如果有人能告诉我这里做错了什么,那就太棒了。非常感谢!

祝你好运, 安东

2 个答案:

答案 0 :(得分:1)

首先,我认为你回错了......

试试这个:

/***
    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 );

答案 1 :(得分:0)

感谢大家的快速回复!我刚刚想出了一个适合我的解决方案:

function() {
  var items = {{dl_products_checkout}};
  var itemsValue = [];
  var sumValue = 0;
  var i, len;
  for (i = 0, len = items.length; i < len; i++) {
    itemsValue.push(items[i].price);
        for (i = 0; i < itemsValue.length; i++){
          sumValue = sumValue + parseFloat(itemsValue[i])
        }
  }
  return sumValue;
}

度过美好的一天!