0

I am trying to create javascript variable dynamically.

var id = "_wuserId"

I need to create a variable

var _wuserId_editor = new Editor();

I have tried

var eval(id + "_editor") = new Editor();

Above code doesnt work

I am not quite sure how to use associative array, I have tried following but it didnt work.

var editor_id = ["_wuserId_editor"];

var editor_id[0] = new Editor();

Please help

3
  • Usually, the way to solve this type of issue is to not use named variables, but to either put your values into an array or make them named properties of an object both of which can be manipulated at runtime quite easily. Commented Jun 4, 2014 at 0:58
  • I think it will be easier to use those dynamic names as object key than as variables Commented Jun 4, 2014 at 0:59
  • I have updated code to reflect what I have tried Commented Jun 4, 2014 at 2:32

2 Answers 2

1

You can't... but you can build an object to stores them (it looks like an associative array when you use it)

var varx['the_id']="whatever"

Sign up to request clarification or add additional context in comments.

Comments

0

Since global variables are part of the window object, just access them via

window["x_" + string]

Or put them in an own associative array.

The same works with other objects, and also with this. Get creative!

var a = {};
a.foobar = 42;
a.foo = function() {
    var s = "bar";
    alert(this['foo' + s]); // prints 42
}

Another way would be to use eval

var b = eval("x_" + string);

But be aware of eval's dangers: When is JavaScript's eval() not evil?

1 Comment

Interesting... Should be considered (or in fact they are) variables properties of the "window object"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.