I have multipled arrays and a selector
variable, now I want to choose and display the corresponding array to in console e.g.:
if (selector == 1) {console.dir(array1)};
However I feel using many if clauses to select an array is unefficent and I need a better approach.
Asked
Active
Viewed 1,433 times
1
-
1Use arrays of arrays or objects with keys. You should never have unknown variable names. – Sebastian Simon May 03 '18 at 10:53
-
Still a duplicate of https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript (despite the question being reopened) – Quentin May 03 '18 at 10:57
3 Answers
2
You can have an array of arrays and use that (your selector is basically the integer index of the array you want in the main array):
var masterArray = [ [1,2] , [3,4] ];
var selector = 1;
console.log(masterArray[selector]) //logs the second item [3,4]
console.log(masterArray[selector - 1]) //logs the first one [1,2] - use this if your selector is not zero indexed
EDIT : Elaborating on @Xufox comment on the question
You can also use an object and access your arrays like this:
var myArrays = {
array1: [1,2],
array2: [3,4]
}
var selector = 1;
console.log(myArrays['array'+selector]) //[1,2]

Chirag Ravindra
- 4,760
- 1
- 24
- 35
0
I recommend to use an object instead. Like so:
var selectors = {
sel1: [
0,
5
],
sel2: [
5,
6
]
};
var i = 1;
console.log(selectors["sel" + i]);

11AND2
- 1,067
- 7
- 10
0
You can create nested arrays(array of arrays) in javascript like the way below if you want:
var arr=[];
for(var i=0;i<10;i++)
{
arr[i]=new Array([i*2,i*3]);
}
// Then using the selector you can retrieve your desired value:
var selector=1;
alert(arr[selector]);//2,3
alert (arr[3]); //6,9
alert(arr[2]); //4,6
alert(arr[2][0][0]); //4
alert(arr[2][0][1]); //6

Rashedul.Rubel
- 3,446
- 25
- 36