返回多个数组中的值

时间:2015-04-23 14:51:36

标签: javascript arrays multidimensional-array

我的程序在单个数组中返回值:[" addEcommerceItem"," hat",29.99," addEcommerceItem"," belt" ,19.99];

我正在努力实现([" addEcommerceItem"," hat",29.99],[" addEcommerceItem"," belt", 19.99]);

任何人都可以提出建议

products = [
    ["hat", 29.99],
    ["belt", 19.99]
]

var testArray = new Array();

for(i in products){
    testArray.push('addEcommerceItem');
    testArray.push(products[i]);
}

var json = JSON.stringify(testArray);

<script type="text/javascript">
  var _paq = _paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  _paq.push(json);
</script>

3 个答案:

答案 0 :(得分:2)

首先,don't use for in enumerations on arrays

现在,有两种方法可以达到您想要的结果。首先,您可以通过将该项添加到每个数组来简单地更改现有数组:

for (var i=0; i<products.length; i++)
    products[i].unshift("addEcommerceItem");

console.log(JSON.stringify(products));

如果那不是您想要的,那么您将构建一个新的数组:

var _paq = […]; // somewhere

for (var i=0; i<products.length; i++)
    _paq.push(["addEcommerceItem"].concat(products[i]));

console.log(JSON.stringify(_paq));

而不是concat,你当然可以使用第二个循环:

var _paq = […]; // somewhere

for (var i=0; i<products.length; i++) {
    var product = products[i],
        temp = [];
    temp.push("addEcommerceItem";
    for (var j=0; j<product.length; j++)
        temp.push(product[j]);
    _paq.push(temp); // push each array individually
}

console.log(JSON.stringify(_paq));

答案 1 :(得分:0)

要获得所需的输出,我已将for-loop修改为spliceproducts数组的附加值,而不是将其推送到testArray

var testArray = new Array();

for (var i=0; i < products.length; i++){
    products[i].splice(0,0,'addEcommerceItem');
    testArray.push(products[i]);
}

可以看到演示结果的JS Bin here

答案 2 :(得分:0)

只需编写您想要发生的事情:将每个子数组替换为"addEcommerceItem"预先渲染的元素。您可以使用concat

function prepend(item) { return ["addEcommerceItem"] . concat(item); }

或者,如果您愿意,

function prepend(item) { item.unshift("addEcommerceItem"); return item; }

然后就是

function transform(products) { return products . map(prepend); }

样本用法:

>> products = [ ["hat", 29.99], ["belt", 19.99] ]
>> transform(products)
<< [ ["addEcommerceItem","hat",29.99], ["addEcommerceItem","belt",19.99] ]

要将结果数组中的每个项目作为一个参数调用_paq.push,然后

_paq.push.apply(_paq, transform(products))

在ES6中:

var prepend   = item     => ["addEcommerceItem", ...item];
var transform = products => products . map(prepend);

_paq.push(...transform(products));