前言:怎么将字符串当代码执行。有 4 中方式实现 eval、setTimeout、创建 script 标签、new Function
1. eval
特点:同步执行,当前作用域
var name = "yq";
function exec(string) {
  var name = "yqcoder";
  eval(string);
}
exec("console.log(name)");
console.log("end");
2. setTimeout
setTimeout 的第一个参数可以传字符串的,自动将这个字符串当作代码来运行
特点:异步执行,全局作用域
var name = "yq";
function exec(string) {
  var name = "yqcoder";
  setTimeout(string);
}
exec("console.log(name)");
console.log("end");
3. 创建 script 元素
特点:同步执行,全局作用域
var name = "yq";
function exec(string) {
  var name = "yqcoder";
  const script = document.createElement("script");
  script.text = string;
  document.head.appendChild(script);
}
exec("console.log(name)");
console.log("end");
4. 使用 Function
特点:同步执行,全局作用域
var name = "yq";
function exec(string) {
  var name = "yqcoder";
  new Function(string)();
}
exec("console.log(name)");
console.log("end");










![[Algorithm][动态规划][完全背包问题][零钱兑换][零钱兑换Ⅱ][完全平方数]详细讲解](https://img-blog.csdnimg.cn/direct/66f39ee7f6384cde94199ab642e70d45.png)





![[Leetcode]同时进行正向和逆向迭代匹配解决回文链表问题](https://img-blog.csdnimg.cn/direct/bcfa69b9b89d4528a4c7fe1d65cfe9d7.png)


