将字符串转换为 JavaScript 对象 - 有没有比使用 eval 更安全的方法?
理想情况下,我希望创建一个简化的界面,要求用户选择三个单选按钮之一,如下所示:
<form id="icon-type">
<input type="radio" name="icon" value="apples" /> Apples
<input type="radio" name="icon" value="oranges" /> Oranges
<input type="radio" name="icon" value="graphes" /> Grapes
</form>
使用 jQuery,很容易确定选择了三个单选按钮中的哪一个:
var iconType = $('input[name=icon]:checked').val();
但是,我需要将分配给的字符串转换为iconType 为先前创建的同名对象。我读到 eval()
是执行此操作的最佳方法,但也遇到了许多警告,指出不应使用 eval()
。然而,似乎没有其他方法可以执行此转换。因此我的问题是:虽然我认识到 eval() 肯定会被滥用,但在这种情况下 eval() 确实是合适的方法吗?
非常感谢!
编辑:@DVK,谢谢!但还是有点失落;假设我的对象如下所示:
var apple = new GIcon(baseIcon);
apple.image = "http://localhost/images/apple.png";
var orange = new GIcon(baseIcon);
orange.image = "http://localhost/images/orange.png";
所以我需要将从所选单选按钮检索到的值转换为适当的对象引用。正如您所解释的,我如何将这些存储在哈希中?谢谢!
I'd ideally like to create a streamlined interface which requires the user to select one of three radio buttons such as shown here:
<form id="icon-type">
<input type="radio" name="icon" value="apples" /> Apples
<input type="radio" name="icon" value="oranges" /> Oranges
<input type="radio" name="icon" value="graphes" /> Grapes
</form>
Using jQuery it's easy to determine which of the three have been selected:
var iconType = $('input[name=icon]:checked').val();
However, I need to convert the string assigned to iconType to an previously created object of the same name. I've read that eval()
is the best way to do this, but have also encountered numerous warnings stating that eval()
should never be used. However there seems to be no other way to perform this conversion. Thus my question: while I recognize that eval()
can certainly be misused, is this a case where eval()
is indeed the appropriate approach?
Thoughts much appreciated!
EDIT: @DVK, thanks! Still a bit lost though; suppose my objects look like this:
var apple = new GIcon(baseIcon);
apple.image = "http://localhost/images/apple.png";
var orange = new GIcon(baseIcon);
orange.image = "http://localhost/images/orange.png";
So I need to convert the value retrieved from the selected radio button into the appropriate object reference. How would I store these in a hash as you explain? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于像这样的简单字符串,您还可以简单地将匹配的对象存储在哈希中,并像这样访问
var obj = object_map[iconType];
For simple strings like this, you can also simply store the matching objects in a hash, and access like this
var obj = object_map[iconType];
您还可以将对象直接链接到输入。
You can also link the object directly to the input.