0

Problem with example:

Variable name: var product5519 = 10;

I can get this name in the form of a String i.e

var str = "product5519"

Is there any way to convert it into variable name so that i can use the value assigned to

product5519

I know one way to solve this problem i.e using eval(str)

If there is any another way to solve it please tell?

Dixit Singla
  • 2,540
  • 3
  • 24
  • 39

4 Answers4

1

Once you are certain creating a global variable was the Right Thing to do, you can add your variable to the window object, like so:

window[str] = 42;

This works because variable lookups end up trying the window object if the variable was not defined in an inner scope.

1

It's a bit hacky but if you wanted to make a global variable you could do:

var str = "product5519";
window[str] = value;

You could then access the variable like:

window[str];
window.str;
str;         // Assuming that there is no local variable already named "str"
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
1

you could do something like:

window['product5519'] = 'value'

it may be better to have an array of products, depending on the situation ofc.

Nathan
  • 146
  • 1
  • 8
0

You can use an associative array:

var variables = [];
variables['product5519'] = 10;

console.log(variables['product5519']);
Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73