1

Im wonder if it is possible to use a string from a varible to identify another varible with an array?

Im runing the code on chrome.

See code to see what i mean.

Thanks!

var box_1 = new Array()

var boxid;

boxid = "box_1";

boxid.push("Is this possible?");
Skolmen
  • 11
  • 3

3 Answers3

1

Answer inside the array:

var box_1 = new Array()
var boxid;
boxid = "box_1";
this[boxid].push("Is this possible?");
this[boxid].push("Yes it is (but your probably should not)");
console.log(box_1);
giuseppedeponte
  • 2,366
  • 1
  • 9
  • 19
  • Why shouldn't I use ´this[boxid]´? – Skolmen Oct 18 '19 at 15:59
  • You should usually beware of global variables, since they can be overwritten at any moment. At least you should try to namespace them to avoid name collision. And also the actual value of this can change depending on the execution context of your code. The bottom line is: if you need dynamic variable names use an object and the bracket notation to access its properties. – giuseppedeponte Oct 18 '19 at 16:41
1

classical way

use an object to refer your array

let obj = {
    box1 : []
};
obj['box1'].push('ok!')
console.log(obj.box1)

bad

beware of eval, just avoid it

let box1 = []
eval('box1.push("brrr")')
console.log(box1)
grodzi
  • 5,633
  • 1
  • 15
  • 15
0

If you are running this on browser, you can access the variable through property accessor like this

var box_1 = new Array()

var boxid;

boxid = "box_1";

window[boxid].push("Is this possible?");

Output:

box_1 < ["Is this possible?"]

pavi2410
  • 1,220
  • 2
  • 12
  • 16