Reputation: 1225
I saw some posts about jQuery's lack of variable variables (like php) and I was wondering how do I handle a situation like this? When I want to use the variable "i" to select an array.
var arr1_1 = ["1","1","1","0","0","0","0","0","0"];
var arr1_2 = ["1","0","0","0","1","0","0","0","1"];
var arr1_3 = ["0","0","0","1","1","1","0","0","0"];
var arr1_4 = ["0","0","0","0","0","0","1","1","1"];
var arr1_5 = ["0","0","1","0","1","0","1","0","0"];
var arr1_6 = ["1","0","0","1","0","0","1","0","0"];
var arr1_7 = ["0","1","0","0","1","0","0","1","0"];
var arr1_8 = ["0","0","1","0","0","1","0","0","1"];
for(var i=0; i <= 9; i++){
console.log(
arr1_"here is the i";
)
}
Upvotes: 1
Views: 51
Reputation: 3176
I believe that you can achieve what you are trying to do with the eval
function
for(var i=0; i <= 9; i++){
console.log(
'here is the arr1_'+i+': ' + eval('arr1_'+i);
)
}
Upvotes: 1
Reputation: 19765
I would go with an array of arrays:
var arr = [
[] /* 0th index - confused about your example - start with 1? */
,["1","1","1","0","0","0","0","0","0"]
,["1","0","0","0","1","0","0","0","1"]
,["0","0","0","1","1","1","0","0","0"]
,["0","0","0","0","0","0","1","1","1"]
,["0","0","1","0","1","0","1","0","0"]
,["1","0","0","1","0","0","1","0","0"]
,["0","1","0","0","1","0","0","1","0"]
,["0","0","1","0","0","1","0","0","1"]
];
for(var i=0; i <= 9; i++) {
console.log(arr[i]);
}
You can then access individual members
arr[row][col];
Upvotes: 0
Reputation: 55740
It is a better idea to store this as a hash, as your data will be structured.
var data = {
"arr1_1": ["1", "1", "1", "0", "0", "0", "0", "0", "0"],
"arr1_2": ["1", "0", "0", "0", "1", "0", "0", "0", "1"],
"arr1_3": ["0", "0", "0", "1", "1", "1", "0", "0", "0"],
"arr1_4": ["0", "0", "0", "0", "0", "0", "1", "1", "1"],
"arr1_5": ["0", "0", "1", "0", "1", "0", "1", "0", "0"],
"arr1_6": ["1", "0", "0", "1", "0", "0", "1", "0", "0"],
"arr1_7": ["0", "1", "0", "0", "1", "0", "0", "1", "0"],
"arr1_8": ["0", "0", "1", "0", "0", "1", "0", "0", "1"],
}
for(var i=0; i <= 9; i++){
console.log(
data["arr1_" + i]
)
}
Upvotes: 2
Reputation: 3974
You can retrieve the variable by the bracket operator in JavaScript:
for(var i=0; i <= 9; i++) {
var varName = 'arr1_'+(i+1);
console.log(window[varName]);
}
Assuming that your array variables are within the 'window' scope.
Upvotes: 0