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.
-
1Use arrays of arrays or objects with keys. You should never have unknown variable names.Sebastian Simon– Sebastian Simon2018-05-03 10:53:00 +00:00Commented May 3, 2018 at 10:53
-
Still a duplicate of stackoverflow.com/questions/5117127/… (despite the question being reopened)Quentin– Quentin2018-05-03 10:57:41 +00:00Commented May 3, 2018 at 10:57
Add a comment
|
3 Answers
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]
Comments
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