1

I have this code:

  createNewDice = () =>{
    let dice;
    for(var i=0; i < 6; i++){
      dice[i] = new Dice();
    }
    console.log(dice, 'dice')
  }

when I call the method I get an error Cannot set property '0' of undefined

Is this not the way to create a new instance of my class?

0

2 Answers 2

1

You are trying to set the property to an undefined variable so before trying to define property initialize variable as an array.

let dice = [];
Sign up to request clarification or add additional context in comments.

Comments

1

You need to initialize dice as an array first.

createNewDice = () =>{
  let dice = [];
  for(var i=0; i < 6; i++){
    dice[i] = new Dice();
  }
  console.log(dice, 'dice')
}

Edit for comment -

If you want to name them then do what Pranav suggested in using an object. I would possibly take a different approach than Pranav suggested though and do something along the lines of -

const dice = {
  one: new Dice();
  two: new Dice();
  ...
  six: new Dice();
};

2 Comments

also how would I name it ? e.g. diceOne, diceTwo etc
@Theworm : use an object and define property name with diceOne, diceTwo, etc...

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.