假设表达式为:
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/