考虑以下代码。 JsFiddle
var a = { prop : 1};
var b = { prop : 2};
var c = { prop : 3};
var d = { prop : 4};
var e = { prop : 5};
var obj = { a : a, b : b, c : c, d : d, e : e, f : 'f stands for fail' };
$(function(){
console.log('try/catch');
try{
for(var p in obj){
if (typeof p != 'undefined')
console.log(eval(p));
}
}catch(e){}
});
$(function(){
console.log('check typeof and you will get string');
for(var p in obj){
if (typeof p != 'undefined')
console.log(eval(p));
}
});
有没有一种方法可以在不必使用 try catch
的情况下检查“oneliner”(如 typeof p != 'undefined'
),这样就可以得到内容的指示无论出于何种原因,eval()
都是不可评估的。基本上,如果评估没有错误,则以某种方式获得 true
,如果失败,则获得 false
。
最佳答案
您可以使用 Function
构造函数检查代码在语法上是否有效而无需对其进行评估。
function isSyntacticallyValid(p){
try {
new Function(p);
return true;
} catch(e){} // e will typically be a SyntaxError
return false;
}
在一般情况下,根本不可能提前检查代码是否真的会在完成时正确无误地求值(这是一个不可判定的问题)。
示例:
var codes = [
"y = x+2", // is OK
"alert('Hey!')", // this one too
"random garbage" // but not this one
];
codes.forEach(function(p){
try {
new Function(p);
} catch(e){
console.log("Bad code : ", p);
}
});
关于javascript - 如果可以评估它并防止异常,如何安全地使用 eval() javascript 来获得指示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24801923/