How do I convert a string into an executable line of code in Javascript?

后端 未结 5 620
盖世英雄少女心
盖世英雄少女心 2020-12-09 09:48

I have the following bit of code

console.log(\"I am\");

var x = \"console.log(\'Alive!\')\";

Now I only want to use x to exec

5条回答
  •  盖世英雄少女心
    2020-12-09 10:28

    What you are looking for is called a function:

    function x() {
        console.log('Alive!');
    }
    

    If x is already a string containing the code you could use eval(x) to execute it. eval is evil though.

提交回复
热议问题