1

I need to set a local variable inside a for loop in a function, but part of the name of this var needs to be a string, more specifically an array index.

See the example:

function MyFunction () {
    var strings = ["first","second","third","fourth"];

    for (var i = 0; i < strings.length; i++) {
        var "My_" + strings[i] + "_var" = "Hi, I'm the " + strings[i] + " var!";
    }
}

I know this is not the correct way, I'm just illustrating what I want to do. I've already tried using window[] or this[], but seems like the var becomes global.

1 Answers1

0

A way is using objects you can make the object's variable name a string using bracket notation

 var obj = {};
 var name = ['first'];
 obj[name[0]]='whatever';

Last but not a secure way is using:

eval('var '+name+' = '+value+';');

Eval evaluate the string as a javascript command therefore you can make up your variables with their names made dynamically.

zardilior
  • 2,810
  • 25
  • 30
  • Using `eval` can be insecure. Ensure that no part of it can be entered by a user. – try-catch-finally Dec 21 '14 at 22:45
  • anyone can run js on the console so they can run any string as js code so it makes no difference – zardilior Dec 21 '14 at 22:46
  • 1
    If anyone stumbling upon this answer I going to use this on a production website this can create security issues. Your answer is perfectly right, I just wanted to mention [the problem of `eval()`](https://jslinterrors.com/eval-is-evil) – try-catch-finally Dec 21 '14 at 22:51
  • Yeah I know your concerns but as I mentioned javascript code can be run in your website even if you don't put any evals. The problem with eval is in languages like php, etc. – zardilior Dec 21 '14 at 22:53
  • 1
    I know this is old as hell, but I leave this here for anyone reading in the future. It can be hard to imagine. Of course anyone can run code on their own console. But the problem is letting *someone else* run code on the user's machine when you fetch and eval data from a database. Imagine Twitter using `eval()` to render tweets. You tweet some code and suddenly you're running it on every person that gets your tweet's machine. That's the issue with XSS. – Gabriel Feb 21 '21 at 17:33
  • @Gabriel thanks for the advice, think you can edit the answer to include this? because I agree this is pretty dangerous – zardilior Apr 29 '21 at 17:05