Search code examples
javascriptvar

Is it possible to use a variable with a string to identify another varible?


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?");

Solution

  • 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)