2

Say I have two arrays and an integer.

var int = 1; //or 0 depending on other circumstances
var ar0 = [0]
var ar1= [1]

Is there a way to use the integer to determine which array to write to? Like if int = 1 then I could have something along the lines of

'ar'+ int

that would choose the correct array? Or do I need a bunch of if-statements? I'd like to be able to identify and edit the array that I need to edit by a number that was given to me.

Andrew McKeighan
  • 121
  • 1
  • 11
  • 2
    Possible duplicate of [Convert string to variable name in Javascript](http://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript) – Leeish Apr 29 '16 at 22:32

2 Answers2

4

What you are trying to do is to set up an environment. However, you cannot access variables in what is called the Variable Environment in JavaScript by name such as with 'ar' + int. If it is in the global scope that is kind of possible by using window['ar'+int] but this is bad practice and also assumes that the variable is global.

What you should do is wrap those in an object and then use the reference in the object to locate the array.

var int = 1;
var environmentObject = {};
environmentObject['ar0'] = [0];//string notation assignment example
environmentObject.ar1 = [1];//dot notation assignment example

and now you can easily access your array by name

var myarr = environmentObject[`ar`+int];
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

You could use an eval

var int = 1;

var ar0 = [0];
var ar1 = [1];

eval('ar' + int).push(2);  

console.log(ar1); // 1, 2

But it is a bad practice. For your case, if you have only two integers(0, 1) better to use if statement:

if(int) { // 0 is falsy, 1 is truth
    ar1.push(...);
} else {
    ar0.push(...);
}

Or as Oriol mentioned, using ternary operator:

(int ? ar1 : ar0).push(...);
Community
  • 1
  • 1
isvforall
  • 8,768
  • 6
  • 35
  • 50