user1082764
user1082764

Reputation: 2015

finding information inside of nested arrays

I have an array that stores the values:

var array = [['favorite color'],['black','red']]

to get black I would:

document.write(array[0][1][0]);

then if i append to the array another question [['favorite thing']['box','ball']]

If I wanted ball I would:

document.write.array[1][1][1];

I am having trouble understanding arrays. I want an array with one question and multiple answers then I want to loop through them and display everything. I can do the loop but I am unsure how to find things in nested arrays once I create them.

Upvotes: 0

Views: 62

Answers (2)

gideon
gideon

Reputation: 19465

var array = [['favorite color'],['black','red','blue']];
document.writeln(array[1][1]);
document.write(array[1][2]);

​ Would print red then blue see it working live : http://jsfiddle.net/HJ872/

How?

array[0] => gets an *array* = ['favorite color'] 
           => array[0][0] gets this first element `favorite color`

array[1] => also gets this array = ['black','red','blue'] 
            => and then [1][1] will get 'red', [1][2] will get `blue`

Upvotes: 0

yas
yas

Reputation: 3620

Use a combination of objects (which work like dictionaries) and arrays. For example:

var array = [ 
  {'question' : 'favorite color', 'choices' : ['black','red'] },
  {'question' : 'favorite thing', 'choices' : ['box','ball'] }
]

for( var i = 0; i < array.length; i++ ) {
    var question = array[i]['question'];
    var choices = array[i]['choices'];

    // here you can display / write out the questions and choices
}

Bearing in mind, creating a class and using a constructor or init methods would probably be better to encapsulate the idea of questions and answers. But the above is the basic idea.

Upvotes: 3

Related Questions