1

forgive me, as I am still new so I hope I am explaining this so it makes sense

I wanted to push multiple items into the addItem function (for instance) console.log("forks", "laptop", "juice") I am able to only push in first item. If I split the strings into separate arguments, when I call back the function, I only get the last argument.

 const cart = { contents: [], addItem(item) { cart.contents = (item) contents.push(...item); //tried it with and without the spread operator. }, removeItem(deletedItem) { delete cart.contents[deletedItem]; } }; cart.addItem("laptop"); cart.addItem("guitar"); cart.addItem("phone"); cart.removeItem("guitar") console.log(`The cart contains: ${cart.contents}`); 
1
  • Get it to for loop over the passed array Commented Aug 18, 2021 at 1:47

2 Answers 2

1

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().

Sign up to request clarification or add additional context in comments.

Comments

1

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}`);

1 Comment

just one small criticism - reassigning the value of cart.contents is not the same as pushing to it - no difference in the small snippet of code shown, but may break something somewhere else

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.