请考虑以下代码。 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));
}
});
有没有办法检查'oneliner'(如typeof p != 'undefined'
),而不必使用try catch
表明eval()
的内容因任何原因无法估量。基本上以true
某种方式获得false
如果它没有错误,并{{1}}如果它失败。
答案 0 :(得分:4)
您可以使用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);
}
});