[英]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() 有没有使用eval()的替代方法
Or which of these is better: 或以下哪个更好:
1. 1。
var _ = variables;
for (var i = 0; i < 100000; i++) {
_.test1();
_.test2();
_.test3();
}
2. 2。
with (variables) {
for (var i = 0; i < 100000; i++) {
test1();
test2();
test3();
}
}
3. 3。
var test1 = variables.test1,
test2 = variables.test2,
test3 = variables.test3;
for (var i = 0; i < 100000; i++) {
test1();
test2();
test3();
}
4. 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: 通过查看您的评论 ,您似乎最关心的问题是必须多次引用一个深层嵌套的对象,避免使用eval
with
我只建议您使用别名标识符,例如:
// 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. 在这样的深度嵌套对象都已经得到解决,并引用您的别名会更快, eval
并with
IMO只会使你比在这种情况下,利益更多的问题。
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: 它不会使属性成为局部变量,但是您可以使用this
关键字访问它们:
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()... 在不使用eval()的情况下,不知道变量名就无法设置局部变量...
...But using local variables ( option 3 ) is the best way. ...但是使用局部变量( 选项3 )是最好的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.