0

I'm creating a simple question and answer game to help with revision and having trouble repopulating an array the second time around.

When a button is clicked the following code is executed.

if(setSelection == 0){
    tempQuestions = chosenQuestion;
    tempAnswers = chosenAnswer;
}

This works perfectly the first time.

When a correct answer is selected the following code removes the question and answer from temporary array, leaving the original intact.

    tempQuestions.splice(randomQuestion,1)
    tempAnswers.splice(selectedAnswer, 1);

When the button is pressed for a second time, after the 'game' is complete, the temporary array fails to refill even though I'm executing the same code.

Any ideas why the code above does not work on the second run?

EDIT

jsfiddle

tonyedwardspz
  • 1,707
  • 2
  • 22
  • 45

2 Answers2

1

You are creating a new reference to the same array, so when you modify the temp vars you also modify the object referenced by the chosen vars. You need to copy the array. A nice way is to add your own copy() prototype method to the Array object.

a shallow copy should do:

Array.prototype.copy = function(){
    return this.slice(0);
}

If you need a deep copy

Array.prototype.copy = function(){
    return JSON.parse(JSON.stringify(this));
}

Use it like this:

if(setSelection == 0){
    tempQuestions = chosenQuestion.copy();
    tempAnswers = chosenAnswer.copy();
}
Preston S
  • 2,751
  • 24
  • 37
0

Using .slice works.

tempQuestions = chosenQuestion.slice();

The slice() operation clones the array and returns reference to the original.

tonyedwardspz
  • 1,707
  • 2
  • 22
  • 45