skyeyl skyeyl -4 years ago 94
jQuery Question

Create a nested array?

I'm creating a trivia game which will give the user 4 answer to pick from. Is using an array to include the question and the answer a good option for this game? and if so what is the proper way to create a nested array.

Answer Source

So... in js it's not a problem to make a nested array, but it is a problem if you're thinking of key => value type of array, in that case you need to use an object, you can foreach it's properties as you would with array IF you'd need to. You can store answer values in array (I've been there with exactly the same thing you want to do so trivia learning game), but you can always use objects and do something like that

var userAnswer = 'something',
    item = {
      question: 'what is a?'
      answers: [ 'a', 'b', 'c' ]
      validAnswer: 0;
    }

if(userAnswer === item.answers[validAnswer]) { 
  console.log("is valid");
}

some other usage:

var userStats = { 
   status: 'alive',
   makeDead: function() {
       this.status = 'dead';   
  },
  bringBackToLife: function() {
       this.status = 'alive';   
  },
}
//then you can even do things like...
userStats.makeDead();
console.log(userStats); //user will be dead
userStats.bringBackToLife(); //user status will be alive

I mean you should be fine with array for keeping just question or question and (nested[[]]) array of answers, but then you're starting to play game of array[0] (should be question right?) array[3] (should be invalid answer?) and then what? if you still think your trivia game will never grow then you might stick to that solution, but if you think it might ever evolve just use objects to keep stuff organised.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download