我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
我如何执行一些JavaScript是一个字符串?
function ExecuteJavascriptString()
{
var s = "alert('hello')";
// how do I get a browser to alert('hello')?
}
当前回答
该方法避免使用潜在风险的eval,提供了可调用的函数,对表达式求值器使用严格模式以获得额外的可靠性,并且比其他答案更简洁。
执行字符串命令
function string_cmd(sCmd) {
new Function(sCmd)();
}
求字符串表达式的值
function string_exp(sCmd) {
return Function(
`'use strict';
return (${sCmd})`
)();
}
用法:
const result = string_exp("2+2");
string_cmd("alert(result)");
https://codepen.io/johnaweiss/pen/mdKpyZL
其他回答
eval(s);
但如果你从用户那里获取数据,这可能是危险的,尽管我想如果他们自己的浏览器崩溃了,那是他们的问题。
该方法避免使用潜在风险的eval,提供了可调用的函数,对表达式求值器使用严格模式以获得额外的可靠性,并且比其他答案更简洁。
执行字符串命令
function string_cmd(sCmd) {
new Function(sCmd)();
}
求字符串表达式的值
function string_exp(sCmd) {
return Function(
`'use strict';
return (${sCmd})`
)();
}
用法:
const result = string_exp("2+2");
string_cmd("alert(result)");
https://codepen.io/johnaweiss/pen/mdKpyZL
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
如果你想在后面执行一个特定的命令(即字符串) 特定的时间 - cmd=你的代码 —InterVal=运行延迟时间
function ExecStr(cmd, InterVal) {
try {
setTimeout(function () {
var F = new Function(cmd);
return (F());
}, InterVal);
} catch (e) { }
}
//sample
ExecStr("alert(20)",500);