gpt4 book ai didi

javascript - eval() 表达式中包含 "return"

转载 作者:行者123 更新时间:2023-12-01 08:33:16 24 4
gpt4 key购买 nike

假设表达式为:

var ex = "console.log(123); return false; console.log(456)"

然后我这样做:

$('#id').change(function(){
eval(ex)
})

当我运行并更改值时,出现错误,“非法返回语句”。问题是“return false”,没有它就没有问题。

假设我无法更改表达式(从 API 获取),如何在保留中断(返回 false)功能的同时评​​估表达式?

最佳答案

您可以将其放入 new Function 中:

var ex = "console.log(123); return false; console.log(456)"

// $('#id').change(function(){
const fn = new Function(ex);
fn();
// })

还可以用 (() => {})(); 包围字符串:

var ex = "console.log(123); return false; console.log(456)"

// $('#id').change(function(){
eval(`(() => {${ex}})();`);
// })

关于javascript - eval() 表达式中包含 "return",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59833086/

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