Andrew McKeighan Andrew McKeighan - 2 years ago 59
Javascript Question

How to write to multiple arrays based off numbers?

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.

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download