2

I am trying to construct the addTopping method such that it can take in multiple toppings to push into the toppings array instead of one. I'm not sure how to tackle this. I've seen some of the other posts using .push.apply() which doesn't work in my case since that creates an object.

  class Pizza {

      constructor(size, crust, stuffedcrust) {
        this.size = size;
        this.crust = crust;
        this.stuffedcrust = stuffedcrust;
        this.toppings = ["Cheese"];
      }

      addTopping(topping) {
        this.toppings.push(topping);
      }

      removeTopping(topping) {
        let index = this.toppings.indexOf(topping);
        this.toppings.splice(index, 1);
      }

      }

      let pizza1 = new Pizza("Medium", "thin", true);

      pizza1.addTopping("Pepperoni", "Green Peppers", "Mushrooms");
      console.log(pizza1);

pizza1.addTopping will only add the first item as of now.

3 Answers 3

4

Use the rest parameters to collect all addToppings() arguments in an array, and the spread syntax to convert the array to arguments for the Array.push() function:

class Pizza {

  constructor(size, crust, stuffedcrust) {
    this.size = size;
    this.crust = crust;
    this.stuffedcrust = stuffedcrust;
    this.toppings = ["Cheese"];
  }

  addToppings(...toppings) { // rest
    this.toppings.push(...toppings); // spread
  }

  removeTopping(topping) {
    let index = this.toppings.indexOf(topping);
    this.toppings.splice(index, 1);
  }

}

let pizza1 = new Pizza("Medium", "thin", true);

pizza1.addToppings("Pepperoni", "Green Peppers", "Mushrooms");

console.log(pizza1);

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

1 Comment

Thank you, I had tried the spread operator before but was incorrectly using it considering I didn't include it within my method arguments as well! This was very helpful, much appreciated!
1

Perhaps take a look over at rest parameters. I think it'll get you what you want

Comments

0

You can use function.arguments, but it is deprecated.

source: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Function/arguments

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.