Skip to content Skip to sidebar Skip to footer

Javascript = Building A Variable Name From Strings

Let's say I have: var acDeMa = [10, 20, 30, 40, 50]; var test1 = 5; var test2 = 7; var test3 = 3; var piece1; var piece2; var piece3; if ( test1 == 5 ) {piece1 = 'ac';} if

Solution 1:

Not really recommended but if you are working in the global context you could use the window object like this

var finishedArray = window[piece1+piece2+piece3];

That will create a reference to your original array. To get a separate copy use the slice method

var finishedArray = window[piece1+piece2+piece3].slice(0)

Solution 2:

Instead of an array, start off with an object:

var myArrays = { acDeMa : [10, 20, 30, 40, 50] }

and then

var finishedArray = myArrays[piece1 + piece2 + piece3];

Post a Comment for "Javascript = Building A Variable Name From Strings"