How to append (concatenate) a variable to a constant in javascript
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.
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).
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.
精彩评论