Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting javascript variable name from a variable

Tags:

javascript

Hi is it possible to set a var name from another variable?

Such as I have the var test with different numbers each time the function is called so I want the number to be a variable name e.g. var test contains ' 1 ' so the new variable would be var 1. I then want to add a word to this number "word" to make the new variable become var 1word.

var newNumber = 1;
var newNumber += 'word';
       ^ becomes ' 1 '
the new var name becomes ' 1word '

edit:

function getNumber(newNumber) //  Gets a number, for this example say its the number '1' 
    {

        var newNumber += "something";  //The new varaible will be named "1something" (something can be any word)

    }

Hope I haven't made it sound too confusing, thanks.

like image 205
Elliott Avatar asked Oct 14 '10 15:10

Elliott


2 Answers

Everything in Javascript is basically just an associative array. This means you can use array access notation and dot notation more or less interchangeably. Array access notation provides the feature you are looking for:

object["name"]="foo"

will set a name property on the given object.

If you want to create a global variable then use the window object

window["name"]="foo"

You can also use an expression or a variable in the square brackets

window[someVaribale]="foo";
window["name_" + someVariable]="foo";
like image 95
Ollie Edwards Avatar answered Nov 06 '22 17:11

Ollie Edwards


You can put the variables in an object and index the object using string keys.

For example:

var myData = { };
myData.x1 = 42;
alert(myData["x" + 1]);

You can also initialize the object using object notation:

var myData = { key: 42 };
like image 3
SLaks Avatar answered Nov 06 '22 17:11

SLaks