eval() javascript如何安全地获得指示,如果它可以评估和防止异常

How safely eval() javascript to get indication if it can be evaluated and prevent exceptions?

本文关键字:如果 评估 异常 何安全 javascript 安全 eval 指示      更新时间:2023-09-26

考虑以下代码。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));
    }
});

是否有一种方法可以检查"在线"(如typeof p != 'undefined'),而不必使用try catch,人们会得到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);
  }
});