[英]Push one array into another array
I am a beginner student. 我是初学者。 I have an array called shoppingCart declared at the start of .js .
我有一个名为shoppingCart的数组,在.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. 使用此函数,我想在shoppingCart数组中添加一个新元素,一个双元素数组。 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
现在您可以从
console.log
找到一组对象
As @FelixKling suggested you can avoid the initialization of the empty object and just do: shoppingCart.push({number: numProduct, quantity: quantity});
正如@FelixKling建议您可以避免空对象的初始化,只需执行:
shoppingCart.push({number: numProduct, quantity: quantity});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.