如何在没有 eval() 的情况下做到这一点
for (var i in variables) {
eval('var ' + i + ' = variables[i]');
}
基本上,我想将变量属性传输到局部变量。
是否有使用 eval()
或者其中哪个更好的替代方法:
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();
}
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过查看您的评论似乎您的专业担心的是必须多次引用深度嵌套的对象,避免 eval 和 with ,我只是建议您使用别名标识符,例如:
这样深度嵌套的对象对象已经被解析,并且引用您的别名会更快,在这种情况下,
eval
和with
IMO只会给您带来更多的问题而不是好处。By looking at your comment seems that your major concern is having to reference several times a deeply nested object, avoiding
eval
andwith
I would simply recommend you to use an alias identifier, for example:In that way the deeply nested object will already be resolved and referencing your alias will be faster,
eval
andwith
IMO would only cause you more problems than benefits in this case.一种替代方法是使该对象成为当前范围。它不会使属性成为局部变量,但您可以使用
this
关键字访问它们:这样做的优点是您不会在任何地方复制任何内容,而是直接访问属性。
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 has the advantage that you are not copying anything anywhere, you are accessing the properties directly.
好吧,我自己发布答案。
不能。
如果不知道变量的名称,不使用 eval() 就无法设置局部变量
……但是使用局部变量(选项 3)是最好的办法。
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.