一、实例:

<script>
eval("x=10;y=20;document.write(x*y)");
document.write("<br>" + eval("2+2"));
document.write("<br>" + eval(x+17));
</script>

1.将一个字符串转换为变量名

function string_to_name(string){  
   let _name = 'var new_name=' + string;  
   eval(_name);  
   return _name;  
}  

2.将一个字符串转换为变量并赋值

var str='string';  
var _script='var '+ string +' =123;';  
eval(_script);  
console.log(typeof string);//number  
console.log(string);//123  
string=456;  
console.log(string);//456  

二、业务场景

const body = document.querySelector("body");
const head = document.querySelector("head");

const ruleSet = ruleSets.find(function (v) {
    return originLink.includes(v.host)
 })

 if (body) {
    let fromType = ruleSet.data.metaType ? 'content': 'innerText';

let queryType = ruleSet.data.metaType ? 'head': 'body';

const bookName = eval(`${queryType}`).querySelector(ruleSet.data.bookname)[fromType]; const author = eval(`${queryType}`).querySelector(ruleSet.data.author)[fromType]; const category = eval(`${queryType}`).querySelector(ruleSet.data.category)[fromType]; }


您已经阅读00:00:00欢迎留言评论,喜欢的话就为作者点个赞或者赏颗糖吧! 分享