You can push multiple elements into an array in the following way
var a = [];
a.push(1, 2, 3);
console.log(a);
Answer from amit1310 on Stack OverflowYou can push multiple elements into an array in the following way
var a = [];
a.push(1, 2, 3);
console.log(a);
Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:
var arr = [1];
var newItems = [2, 3];
arr.push(...newItems);
console.log(arr);
See Kangax's ES6 compatibility table to see what browsers are compatible
Videos
You have to make item a rest parameter:
const cart = {
contents: [],
addItem(...item) {
this.contents.push(...item);
},
removeItem(deletedItem) {
this.contents.splice(this.contents.indexOf(deletedItem), 1);
}
};
cart.addItem("laptop", "guitar", "phone");
cart.removeItem("guitar")
console.log(`The cart contains: ${cart.contents}`);
Also, don't use delete to delete an item. Instead, use splice().
you were pretty close with the spread operator, your code just needed a little change, with this change you can pass multiple items as separated values or even an array with multiple items, even multiple arrays with multiple values.
they end always being a plain array of strings, here is your working code.
const cart = {
contents: [],
addItem: (...items) => {
cart.contents = [...cart.contents, ...items];
},
removeItem(deletedItem) {
this.contents.splice(this.contents.indexOf(deletedItem), 1);
}
};
// multiple values
cart.addItem("laptop", "guitar", "phone");
console.log(`The cart contains: ${cart.contents}`);
// array of values
cart.addItem(['new laptop', 'new guitar', 'new phone']);
console.log(`The cart contains: ${cart.contents}`);
// multiple arrays
cart.addItem(['inner laptop1', 'inner guitar1', 'inner phone1'], ['inner laptop2', 'inner guitar2', 'inner phone2'], ['inner laptop3', 'inner guitar3', 'inner phone3']);
console.log(`The cart contains: ${cart.contents}`);
Hey, so maybe this is a silly question but I was wondering how to measure the performance of push method, would it be preferable to push a few elements into an array at once or just push it a couple of times? I'm using console.time method to measure the diff between these two approaches, maybe there is a better/more reliable way to test this?
Example:
// one call to push method
arr.push({a:'a', b: 'b'}, {c:'c', d: 'd'});
// n calls to push method
arr.push({a:'a', b: 'b'});
arr.push({c:'c', d: 'd'});
It's just to see which one is faster more than the obvious thing to do (just push it all in one call)