如何在没有eval()的情况下执行此javascript代码?

时间:2016-07-24 15:38:59

标签: javascript eval

function run(conditions) {
/* --- code --- */
var pages_counter = parseInt(localStorage.getItem('onload_counter'));
var seconds_counter = parseInt(JSON.parse(localStorage.getItem("waiting_for_modal"))[0])+1;
/* --- code --- */
var vared = eval(conditions.test.join(' ')) ? true:false;
if(vared){
jQuery('#myid').fadeOut(500);
}
}

var conditions = {
/* --- code --- */
"test": ["( pages_counter > 1 && seconds_counter > 10 )||( seconds_counter > 40 && pages_counter === 1 )"]
};
run(conditions);

在这种情况下,eval()是危险的吗?或者有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

为什么不为它使用函数?

var conditions = {          
    test: function (pages_counter, seconds_counter) {
        return (pages_counter > 1 && seconds_counter > 10) || (seconds_counter > 40 && pages_counter === 1);
    }
};

// test with
var vared = conditions.test(pages_counter, seconds_counter);