Hi im tying to run javascript from a string/array without eval if possible. here is kinda what I want.
code = ["document.write('hello')", "function(){}"];
code.run[1];
Any help would be appreciated, thanks.
Hi im tying to run javascript from a string/array without eval if possible. here is kinda what I want.
code = ["document.write('hello')", "function(){}"];
code.run[1];
Any help would be appreciated, thanks.
The only way to run javascript from a string is to use eval()
.
Correction: Aside from eval("codeString");
, new Function("codeString")();
will execute your code, too. The disadvantage of this is that your code will have to be interpreted when you when you call new Function(...)
, compared to optimisations the browser may use when pre-defining the code, like the example below.
So, eval("codeString");
and new Function("codeString")();
are possible, but bad ideas.
A better option would be to store functions in a array, like this:
function foo(){
document.write('hello');
}
function bar(){
return 1+2;
}
var code = [ foo,
function(){
alert("Hi there!");
},
bar
];
code[0](); // writes "hello" to the document.
code[1](); // alerts "Hi there!"
code[2](); // returns 3.
You can execute it as a function.
Like this
function yourNewEval(){
var code = ["document.write('hello');", "function(){}"];
var F = new Function(code[0]);
return(F());
}
yourNewEval();
Answer copied from Stefan's answer.
A lot of creative answers in How can I execute Javascript stored as a string?