简体   繁体   中英

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

I have the following bit of code

console.log("I am");

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

Now I only want to use x to execute the code-string that is assigned to it - I may not even know the value of x for example but simply want to execute it whatever it maybe - is this possible?

eval()这会将字符串转换为 javascript 代码。

eval("console.log('Alive! Woo!')");

eval and new Function let you parse and execute JavaScript code from strings.

In general, avoid executing code from strings. And never execute code from strings where the strings are untrusted input (for instance, if you take input from user A, never use these to evaluate it in a session with user B).

I see answers here pointing you at eval . eval grants access to your local variables and such to the code, making it really powerful and really dangerous if you use it with untrusted input.

Where possible, avoid eval . You can easily avoid it in your case:

For instance:

 console.log("I am"); var x = "console.log('Alive!')"; new Function(x)();

That code creates a function whose body is the text from x , then immediately executes the function.

What you are looking for is eval() . By passing a string to this function you will evaluate the string as JavaScript code and it will return whatever return-value the code in the string returns.

Be aware when using this function though. You do not want to evaluate any code you do not know is safe to execute. For example, running user-generated code could mess up whatever you are making. While using this in JavaScript on a website this will probably only cause issues on the client-side and hence probably won't be much of a security threat, you would want to be VERY careful when evaluating code on for example a server side.

As have been hinted to in other posts here you probably want to make a function instead of an evaluated string if you are in control of the source code that is to be run.

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.

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

have the function mathchallenge (num) add up all the numbers from 1 to num for example if the input is 4 then your program should return 10 because 1+2+3+4=10. for the test cases the parameter num will be any number from 1 to 1000

"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM