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

Coder
  • 3,090
  • 8
  • 49
  • 85
  • 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. – jfriend00 Jun 04 '14 at 00:58
  • I think it will be easier to use those dynamic names as object key than as variables – Arun P Johny Jun 04 '14 at 00:59
  • I have updated code to reflect what I have tried – Coder Jun 04 '14 at 02:32

2 Answers2

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"

miguel-svq
  • 2,136
  • 9
  • 11
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?

Community
  • 1
  • 1
Felk
  • 7,720
  • 2
  • 35
  • 65