0

I have created some arrays, example yy1, yy2, yy3, etc., and I am able to display the elements of an array using

for (j=0; j < count; j++){
    alert(yy1[j]);
}

and other arrays by changing number, that is yy2, yy3...

How to display the array in a loop, like

for (i=0; i< lengthL; i++){ 
    for (j=0; j < count; j++){
        alert(yyi[j]);
    }
}

That is how to join yy with i.

Please let me know if I am not clear, thanks in advance.

3
  • 2
    "Please let me know if I am not clear" -- You are not clear. Commented Jun 6, 2011 at 22:53
  • If yy1...yyn are global then you could use window['yy'+i][j] Commented Jun 6, 2011 at 22:56
  • if i=2, I want to display yy2[j] and if i=4, I want to display yy4[j] and soon on. So how to join yy (kind of constant) with i (variable). Please let me know, thanks. Commented Jun 6, 2011 at 22:57

2 Answers 2

4

I believe the asker is saying how to iterate over yy1, yy2 and yy3 in the same loop. The answer is that you should structure your variable differently. If 1, 2 and 3 are really keys, then you should just have one yy array and give each of its "rows" its own array.

In other words, use yy[0], yy[1] and yy[2] instead of yy1, yy2 and yy3. For example, the following is totally valid:

var yy = [
  [0, 1, 2],
  [3, 4],
  [5, 6, 7, 8]
];

// Examples
console.log(yy[0][0]); // returns 0
console.log(yy[1][0]); // returns 3
console.log(yy[2][2]); // returns 7

// Iterating over the whole thing
for (var i = 0; i < yy.length; i++) {
  for (var j = 0; j < yy[i].length; j++) {
    console.log(yy[i][j]);
  }
}

There's no way to do what you're asking that's both easy (i.e. declaring yy1, yy2 and yy3 then filling another array) and free from abuse (i.e. eval is evil here).

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

1 Comment

Thanks for your answer Bryan, I am gonna go with amit_g's eval option.
0

What you are looking for is eval (Warning, Eval is evil!). You can use it to do what you are trying to do but you should rather change the way the data is stored to avoid it. It is very easy in your case (look at other answer for guidance).

var yy1 = [11, 12, 13];
var yy2 = [21, 22, 23, 24, 25];
var yy3 = [31, 32, 33, 34];

for (i = 1 ; i <= 3 ; i++)
{
    var arr = eval("yy" + i);

    for (j = 0 ; j < arr.length ; j++)
    {
        console.log(arr[j]);
    }
}

Demo

You should use Firefox and Firebug so that you can use console.log instead of alert.

2 Comments

There is no need for eval() here: var arr = window['yy'+i] has the same result.
Don't use eval if your variables are global. Although global variables like that in itself are big no no...

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.