动态创建对象,eval 的替代方案是什么?
我正在尝试使用eval(string)
动态创建对象。我一直无法找到使用 eval
的替代方法,或者至少找到我能理解的方法。
我正在循环执行如下所示的代码,该字符串随机变化,为包含对象定义的字符串数组选取。
llista[dia] = eval('new Accident_mortal("EP-8", 17, "accident helicopter", 1, 2, 0)');
从我读到的所有内容来看,使用 eval
是一件坏事,但我不知道还能如何做到这一点。
编辑
我认为 Lolo 的代码正是我需要的,我可以执行以下操作吗?
var o = [
{ clazz1: 'Accident_mortal', args: ["EP-8", 17, "accident helicopter", 1, 2, 0] },
{ clazz2: 'Accident_mortal', args: ["B45", 101, "accident camio", 4, 3, 1] },
{ clazz3: 'Accident_mortal', args: ["C19", 234, "accident tot terreny", 2, 1, 1] }
}
var o 内部最多有 9 个对象,然后使用他提出的代码从这 9 个定义生成随机对象。
I'm trying to create objects dynamically, using eval(string)
. I've been unable to find an alternative to using eval
or at least something that I could understand.
I'm looping through code that looks like the following, the string varies randomly, picked up for an array of strings which contain objects definitions.
llista[dia] = eval('new Accident_mortal("EP-8", 17, "accident helicopter", 1, 2, 0)');
From what I've read all around, using eval
is a bad thing, but I can't figure out how else I could do this.
EDIT
I think Lolo's code is what I need, can I do the following?
var o = [
{ clazz1: 'Accident_mortal', args: ["EP-8", 17, "accident helicopter", 1, 2, 0] },
{ clazz2: 'Accident_mortal', args: ["B45", 101, "accident camio", 4, 3, 1] },
{ clazz3: 'Accident_mortal', args: ["C19", 234, "accident tot terreny", 2, 1, 1] }
}
Up to 9 objects inside var o, and then use the code he proposes to generate random objects from these 9 definitions.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以用对象数组替换字符串数组,那么您可以尝试以下操作:
If you can replace array of strings with array of objects, then you may try this:
另一种替代方案(虽然不一定是改进)是创建
Function
构造函数来评估字符串,并返回新对象。但如果您需要多次
评估
这些字符串中的任何一个,这可能会被证明是理想的。您可以使用新函数覆盖数组的每个成员。
现在,您可以将数组中的每个项目作为函数引用,该函数返回使用给定参数从构造函数创建的对象。
最终,最好的解决方案是不必使用需要评估为代码的字符串。如果这是不可避免的,那么您的选择就很有限。
An alternative, though not necessarily an improvement, would be to create the
Function
constructor to eval the string, and return the new object.But this may prove to be desirable if you need to
eval
any of these strings more than once.You could overwrite each member of the array with the new function.
Now you can reference each item in the array as a function that returns an object created from the constructor with the given arguments.
Ultimately the best solution would be to not have to work with Strings that need to be eval'd into code. If this is unavoidable, your options are limited.