5 || b > 5)"; if(condition) { aler-6ren">
gpt4 book ai didi

javascript - Javascript 中的动态 if 语句

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:39:07 26 4
gpt4 key购买 nike

是否有将字符串转换为 if 语句中的条件的方法:

示例:

var condition = "a == b && ( a > 5 || b > 5)";

if(condition) {
alert("succes");
}

最佳答案

eval() 的更安全替代方案可能是 Function()

var condition = "4 == 4 && ( 10 > 5 || 9 > 5)";
var evaluate = (c) => Function(`return ${c}`)();

if(evaluate(condition)) {
alert("succes");
}

Per MDN:

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

关于javascript - Javascript 中的动态 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55224782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com