我如何执行一些JavaScript是一个字符串?

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    // how do I get a browser to alert('hello')?
}

当前回答

使用eval()。

W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。

你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。

您还需要知道eval()具有不同的作用域。

其他回答

使用eval()。

W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。

你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。

您还需要知道eval()具有不同的作用域。

不确定这是不是作弊:

window.say = function(a) { alert(a); };

var a = "say('hello')";

var p = /^([^(]*)\('([^']*)'\).*$/;                 // ["say('hello')","say","hello"]

var fn = window[p.exec(a)[1]];                      // get function reference by name

if( typeof(fn) === "function") 
    fn.apply(null, [p.exec(a)[2]]);                 // call it with params

eval函数将对传递给它的字符串求值。

但是eval的使用是超级危险和缓慢的,所以要谨慎使用。

检查了许多复杂和混乱的脚本:

var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);

Stefan的回答延伸如下:

//Executes immediately function stringToFunctionAndExecute(str) { let func = new Function(str); return (func()); // <--- note the parenteces } //Executes when called function stringToFunctionOnly(str) { let func = new Function(str); return func; } // -^-^-^- Functions -^-^-^- (feel free to copy) // -v-v-v- Explanations -v-v-v- (run code to read easier) console.log('STEP 1, this executes directly when run:') let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')"); console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:") try { func_A(); } catch (error) { console.log('STEP ERROR, see, it failed', error) } console.log('STEP 3, but this will NOT execute directly AND you can save it for later...') let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')"); console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:") func_B(); console.log('STEP 5, TADAAAAA!!')