javascript - 如果可以评估它并防止异常,如何安全地使用 eval() javascript 来获得指示?

标签 javascript

考虑以下代码。 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/

相关文章:

javascript - Highcharts 堆积百分比列超链接

javascript - AngularJS 设置指令同步调用函数

javascript - 如何在没有jquery的情况下查找集合中元素的索引

javascript - 自定义 AJAX dataType 类型

javascript - Angular-jQCloud : Resize words based on number of words

javascript - 如何从字符串创建日期,忽略任何时区偏移?

javascript - 另一个最接近的子线程 : finding the nearest ancestor of an element that matches a selector

javascript - 在 GWT 应用程序中使用 HTML 页面

javascript - 文本节点添加事件监听器

javascript - 如何使用 Kimono Labs 从网站上抓取整个表格(而不是前十行)