0

I have two variables, varL and varR, which have the information that they are L and R respectively. Depending on wether a third object has as imput 'L' or 'R', I would like to reference varL or varR respectively. Is there any way to do this?

Specifically, varL and varR are arrays. If the third object has as imput 'L', I would like to have access to varL[i] for some i, and the same goes for 'R'. I know this is not even remotely correct, but I was looking for something like

(var +'L')[i] or something

popeye
  • 81
  • 2
  • 5
  • You can use `eval` to do that. – AndreFeijo Apr 06 '17 at 05:22
  • 1
    @AndreFeijo But you shouldn't. – Bergi Apr 06 '17 at 05:32
  • For just two variables, use a simple condition that evaluates to either. For more complex scenarios, use an appropriate data structure that allows lookup by key instead of multiple variables. – Bergi Apr 06 '17 at 05:33
  • Why is it not advisable to use eval? It worked just fine, thanks! – popeye Apr 06 '17 at 05:50
  • @GastonMaffei [Why is it not advisable to use eval?](https://www.google.co.jp/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=why+is+it+not+advisable+to+use+eval&*) – JLRishe Apr 06 '17 at 05:58
  • @GastonMaffei http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Bergi Apr 06 '17 at 06:07

4 Answers4

1
var varL;
var varR;

function getInput(input) {
  return (input == 'L') ? varL : varR;
}

?

mwkrimson
  • 115
  • 1
  • 9
0

If you have input value then you can check and use corresponding array like below in your loop

var testL=[4,5,6];
var testR=[4,5,6];


var input='L';

if(input=='L'){
  console.log(testL[0]);    //replace 0 with i index
}else if(input=='R'){
 console.log(testR[0]);      //replace 0 with i index
}
Love-Kesh
  • 777
  • 7
  • 17
0

Your question is the XY problem. Instead of asking "How can I access a variable by a dynamic name?", you should be asking "How can I access the needed value for L or R dynamically?"

One simple way to make it work is to store the values in an object with .L and .R properties. Then it's very simple to access the needed value:

var myVar = {
  L: [1, 2, 3],
  R: [3, 4, 5]
};

var direction = 'L';

console.log(myVar[direction]);

direction = 'R';

console.log(myVar[direction]);
JLRishe
  • 99,490
  • 19
  • 131
  • 169
-2

Try to access it from window object

window[("var"+"L")]

It will work !!

or eval

eval(("var"+"L"))[i]
RITESH ARORA
  • 487
  • 3
  • 11