简体   繁体   中英

Add first three elements of array in javascript

I am quite new to Javascript so sorry if my question is too basic. I am trying to implement "Criteo tag" in a page and I need to pass three IDs in it.

The provided code from Criteo is

<script type="text/javascript">
window.criteo_q = window.criteo_q || [];
window.criteo_q.push(
{ event: "viewList", item:[ "product_id_1" , "product_id_2" , "product_id_3" ]}
);
</script>

They basically tell you to pass the first three products in a page, within that item element.

I have an array with all product IDs, but I am not sure how to pass it in JS and somehow use a foreach loop and get first product, second product, third product and use it within event - viewlist - item element.

What I'm trying to succeed is something like:

<script type="text/javascript">
var getproducts = array_slice($allproducts, 0, 3);

window.criteo_q = window.criteo_q || [];
window.criteo_q.push(
{ event: "viewList", item:[ getproducts[0] , getproducts[1], getproducts[2] ]}
);
</script>

The above code is probably wrong... Can anyone please lead me to the right way?

Call .slice() chained to $allproducts array

window.criteo_q.push(
 { event: "viewList", item: $allproducts.slice(0, 3) }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM