Javascript替代eval方法

Javascript替代eval方法

通常我们在使用ajax获取到后台返回的json数据时,都要使用 eval 这个方法将json字符串转换成对象数组, 像这样:

obj = eval('('+data+')')

而使用这个方法会导致编辑器中的jshint报错:

JSHint 6:19 eval can be harmful.

SO. 使用替代eval的方法即可拯救强迫症患者:

方法1:

//计算表达式的值
function evil(fn) {
    var Fn = Function;  //一个变量指向Function,防止有些前端编译工具报错
    return new Fn('return ' + fn)();
}

方法2

function eval1 (str) {
    var script = document.createElement('script');
    script.type="text/javascript";
    script.text=str;
    document.getElementsByTagName('head')[0].appendChild(script);
    document.head.removeChild(document.head.lastChild);
}

方法1亲测有效!

原文地址:https://www.cnblogs.com/lxg0/p/7805266.html