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.‏ ‏

10
  • 2
    You don't need dynamically created variable names, use a proper data structure, an array or an object, instead. Commented May 26, 2021 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. Commented May 26, 2021 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.) Commented May 26, 2021 at 15:45
  • 4
    @rikir — Whatever XY problem you have, dynamic variable names are the worst possible solution for it. Use an object. Commented May 26, 2021 at 15:46
  • 2
    @rikir — See the duplicate question. Commented May 26, 2021 at 15:48

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.