Manny Narton
Manny Narton

Reputation: 13

Accessing a specific array

I have a set of arrays named in the following fashion: question0, question1, question2 etc.
I also have a variable that corresponds to the question number.

With this, how would I access array question0 without having to type out the whole name. For example, in a for loop, I have if the loop number is 5, I want to do an operation on question5. I know this is really simple, but I haven't been able to find the solution.

Upvotes: 0

Views: 68

Answers (4)

user1585455
user1585455

Reputation:

I think it would be simpler to have your question(n) values as an array. From there you could use the following: questions[i] where i represents the current loop number, thus improving manipulation.

var questions = [["What?", "Why?"], ["When?", "How?"]];
for(var i = 0; i < questions.length; i++) {
 for(var j = 0; j < questions[i].length; j++) {
  console.info(questions[i][j]);
 }
}

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173562

Don't use variable names with an ordinal number as their suffix; use the proper structures, such as an array:

var questions = ['why?', 'what?', 'where?'],
nr = 2; // the question number

alert(questions[nr]);

In my example, each "question" is a string, but it could be any other structure, including another array.

Upvotes: 1

Ry-
Ry-

Reputation: 224904

Variables ending in sequential numbers are usually a hint to use arrays. Sounds like you need an array of arrays instead, and then you can just:

doOperation(question[somenumber])

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Why not just use a big array, question, where each item it itself an array?

That aside, if the variables are global then you could use window['question'+i], with i being the number of the question.

Upvotes: 1

Related Questions