0

I have an array:

var arr = ['a', 'b', 'c'];

I need to declare within a for loop, variables value_x- when x is each one of the array value.

what I've tried:

var i;
for(i=0;i<3;i++){
    var x = 'hello there';
    var str = 'var ' + `value_${arr[i]}` + ' = ' + "'" + x + "'" + ';'
    eval(str);
}

now, str =

var value_a = 'hello there';

but the eval() call return this error:

error: EvalError: Dynamic code evaluation disallowed‏

now, I saw also solution which used window object, like:

window[`value_${arr[i]}`] = x;

and this also return error:

error: ReferenceError: window is not defined

which because this is local script, not on the server. please help.‏ ‏

riki
  • 187
  • 1
  • 17
  • 2
    You don't need dynamically created variable names, use a proper data structure, an array or an object, instead. – Teemu May 26 '21 at 15:43
  • no, I do need dynamically created variable names. in fact I have dozens of names I want to declare in same logic. – riki May 26 '21 at 15:44
  • 2
    You cannot do that, so you need a Plan B. If you use an object, you can create property names dynamically. (Yes, you can create properties on the global object context, but that's asking for trouble.) – Pointy May 26 '21 at 15:45
  • This seems like a bad solution to whatever your actual problem is. – Nikki9696 May 26 '21 at 15:46
  • 4
    @rikir — Whatever XY problem you have, dynamic variable names are the worst possible solution for it. Use an object. – Quentin May 26 '21 at 15:46
  • JavaScript doesn't have a concept for dynamically created variable names like some other languages have, you've to rethink your logic. – Teemu May 26 '21 at 15:46
  • @Quentin, thanks for you advice. can you please refer me to example for dinamically object properties names? – riki May 26 '21 at 15:48
  • @rikir `obj[keyIsVariable] = valueIsVariable` – VLAZ May 26 '21 at 15:48
  • 2
    @rikir — See the duplicate question. – Quentin May 26 '21 at 15:48
  • Your problem solving via dynamic variables is not a good solution. The wrong design always leads to a difficult solution. My recommendation is to use other data structures such as Array or Object. – Sokmesa Khiev May 26 '21 at 15:50

0 Answers0