简体   繁体   中英

How to do this without eval()

for (var i in variables) {
    eval('var ' + i + ' = variables[i]');
}

Basically, I want to transfer variables properties to local variables.

Is there an alternative to using eval()

Or which of these is better:

1.

var _ = variables;
for (var i = 0; i < 100000; i++) {
    _.test1();
    _.test2();
    _.test3();
}

2.

with (variables) {
    for (var i = 0; i < 100000; i++) {
        test1();
        test2();
        test3();
    }
}

3.

var test1 = variables.test1,
    test2 = variables.test2,
    test3 = variables.test3;
for (var i = 0; i < 100000; i++) {
    test1();
    test2();
    test3();
}

4.

for (var i in variables) eval('var ' + i + ' = variables[i]');
for (var i = 0; i < 100000; i++) {
    test1();
    test2();
    test3();
}

By looking at your comment seems that your major concern is having to reference several times a deeply nested object, avoiding eval and with I would simply recommend you to use an alias identifier, for example:

 // some local scope...
 var foo = namespace.constructors.blah.dramatic.variables;
 // replace foo with something meaningful :)
 foo.method1();
 foo.method2();
 foo.property1;
 // etc...

In that way the deeply nested object will already be resolved and referencing your alias will be faster, eval and with IMO would only cause you more problems than benefits in this case.

One alternative is to make the object the current scope. It won't make the properties local variables, but you can access them using the this keyword:

var variables = { a:42, b:1337 };

(function(){
  alert(this.a);
  alert(this.b);
}).apply(variables);

This has the advantage that you are not copying anything anywhere, you are accessing the properties directly.

Well, I'll post the answer myself.

No.

There is no way to set local variables without knowing the name of the variable without using eval()...

...But using local variables ( option 3 ) is the best way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM