如何在JavaScript中无需eval()匹配选中选项对应的变量名?
替换eval()的安全高效方案
你说得对,eval()确实要尽量避免——它不仅有安全风险(如果menuOptions里的内容被篡改,可能执行恶意代码),而且性能也不如直接的属性访问。这里有个更优雅的替代方案,用对象来管理你的选项集,完全不需要eval():
修改后的代码
$("#type").on("change", function() { var typeVal = $(this).val(); // 把所有选项集放到一个配置对象里 var optionSets = { approved: [{ id: 1, text: "Month" }, { id: 2, text: "Week" }], active: [{ id: 1, text: "Progress" }, { id: 2, text: "No Feedback" }, { id: 3, text: "Office Closed" }], inactive: [{ id: 1, text: "Missing" }, { id: 2, text: "Expired" }], terminated: [{ id: 1, text: "Natural" }, { id: 2, text: "None" }] }; var menuOptions = { "1": "approved", "2": "active", "3": "inactive", "4": "terminated", "5": "inactive", "6": "active" }; var targetSetKey = menuOptions[typeVal]; // 直接通过对象键访问对应的选项集,完全不需要eval! var selectedOptions = optionSets[targetSetKey]; console.log(selectedOptions); });
为什么这更好?
- 安全性:不会执行任何动态代码,所有选项集都是预先定义的,不存在注入风险。
- 性能:对象属性访问是JavaScript里最快的操作之一,比
eval()的解析执行快得多。 - 可读性:代码逻辑更清晰,一眼就能看出你是从预定义的集合里获取数据,而不是执行一段字符串代码。
更进一步的优化(可选)
如果你的menuOptions不需要单独复用,还可以直接把选项集绑定到对应的type值上,省去中间的键映射步骤:
$("#type").on("change", function() { var typeVal = $(this).val(); var optionMap = { "1": [{ id: 1, text: "Month" }, { id: 2, text: "Week" }], "2": [{ id: 1, text: "Progress" }, { id: 2, text: "No Feedback" }, { id: 3, text: "Office Closed" }], "3": [{ id: 1, text: "Missing" }, { id: 2, text: "Expired" }], "4": [{ id: 1, text: "Natural" }, { id: 2, text: "None" }], "5": [{ id: 1, text: "Missing" }, { id: 2, text: "Expired" }], "6": [{ id: 1, text: "Progress" }, { id: 2, text: "No Feedback" }, { id: 3, text: "Office Closed" }] }; var selectedOptions = optionMap[typeVal]; console.log(selectedOptions); });
这样代码更简洁,少了一层映射,逻辑更直接。
内容的提问来源于stack exchange,提问作者espresso_coffee
相关产品推荐
相关产品推荐

