javascript - 从字符串运行 javascript

标签 javascript string

<分区>

您好,如果可能的话,我想从字符串/数组不使用 eval 运行 javascript。这就是我想要的。

code = ["document.write('hello')", "function(){}"];
code.run[1];

如有任何帮助,我们将不胜感激。

最佳答案

从字符串运行 javascript 的唯一方法是使用 eval()
更正:除了 eval("codeString");new Function("codeString")(); 也会执行您的代码。这样做的缺点是当您调用 new Function(...) 时必须解释您的代码,与浏览器在预定义代码时可能使用的优化相比,例如示例下面。
所以,eval("codeString");new Function("codeString")(); 是可能的,但不是好主意。

更好的选择是将函数存储在数组中,如下所示:

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.

关于javascript - 从字符串运行 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509169/

相关文章:

java - 如何在字符串的某个位置添加字符(Java)

python - 需要为每个字符串创建一个数组的数组

javascript - Ajax 表单未在 Chrome 上提交

javascript - JavaScript 中的 "(function(window, undefined){})(window)"是什么意思?

javascript - React-Router-Redux 分派(dispatch) LOCATION_CHANGE 两次,删除搜索值

javascript - 不使用 javascript 或 href 打开一个新窗口

java - 非空字符串的哈希码可以为零吗?

python - 为什么 pandas 字符串系列为 len() 函数返回 NaN?

java - java中提取特定字符串

javascript - 多个音频 html : auto stop other when current is playing with javascript