0

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.

2
  • 2
    "to get black I would: ... array[0][1][0]. No, that would result in an error. This would imply a structure such as [[...,['black',...]], ...]. You would get black with array[1][0] because array has to two elements, both arrays, and you want to get the first element (0) of the second array (1). Commented Mar 12, 2012 at 1:50
  • You can always experiment on jsfiddle.net Commented Mar 12, 2012 at 1:52

2 Answers 2

3

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.

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

1 Comment

This is what i am trying to understand. this helps alot but how would i do this with numbers insead of words. How would i find ball? array[1][1][1]?
0
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`

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.