简体   繁体   中英

Push one array into another array

I am a beginner student. I have an array called shoppingCart declared at the start of .js .

var shoppingCart = [];

I think this is not the most appropriate and professional way to do it, but i don't know more. And then I have the following function:

function addToShoppingCart(numProduct, quantity){
  shoppingCart.push([numProduct, quantity]);
}

With this function I want to add a new element, a two-element array, in the shoppingCart array. I've also tried to do the following:

shoppingCart.push("["+ numProduct + ", " + quantity+ "]");

I want the array looks like this:

shoppingCart = [[numProduct1,quantity1],[numProduct2,quantity2],...,[numProductN,quantityN]]

But it seems to be added as individual elements. What am I doing wrong? How should I do it correctly? Thank you for your help and/or attention.

In general you should first create an object then populate and finally push it in the array:

function addToShoppingCart(numProduct, quantity){
  var product = {}
  product.number = numProduct;
  product.quantity = quantity
  shoppingCart.push(product);
  console.log(shoppingCart)
}

Now you have an array of objects as you can find out from the console.log

As @FelixKling suggested you can avoid the initialization of the empty object and just do: shoppingCart.push({number: numProduct, quantity: quantity});

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