+ 4

Eval() function use in JavaScript.

I'm trying to create lots of different variables dynamically in JS, with their names being appended with different numbers. Using the function eval() is the only way I can think of to do this (see https://code.sololearn.com/WfWQILeikZSj/?ref=app to see the sort of thing I'm trying to do), but I've heard that eval() can be both slow and insecure. Is there another way of doing this, or is this a reasonable use for this function? Thanks in advance.

23rd Jul 2018, 2:16 PM
Russ
Russ - avatar
4 Respostas
+ 16
You should use window["num"+i]=i not eval. Though this will work only on browser. In Node.js you would have to use global instead of window. Btw why are you doing this ? Use arrays instead. var nums=[]; nums[i]=i; Or use an object so that the global scope is not polluted. var numObj={}; numObj["num"+i]=i;
23rd Jul 2018, 2:30 PM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 14
Russ you can use window for global scope (in browser) but for local scope there is no such object. You can create a local variable as an Array or Object and assign keys to it as shown above.
23rd Jul 2018, 2:48 PM
Swapnil Srivastava
Swapnil Srivastava - avatar
+ 4
‌S‌w‌a‌p‌n‌‌il S‌r‌iv‌‌ast‌av‌a Thanks, that seems to work! Does that make them global variables? Is there a way to make them local? Just curious, really - not sure if it's necessary. Edit: each variable is actually going to be an array itself, and in array, to make a 2D array. I haven't experimented using unnamed arrays in an array as I'm still new to this, but I will try it now. Thanks again for your help.
23rd Jul 2018, 2:37 PM
Russ
Russ - avatar
+ 4
‌S‌w‌a‌p‌n‌‌il S‌r‌iv‌‌ast‌av‌a I can see now that that is a much simpler and cleaner way to do this. Many thanks to you for your help!
23rd Jul 2018, 2:52 PM
Russ
Russ - avatar