如何将字符串转换为Javascript中的可执行代码行? [英] How do I convert a string into an executable line of code in Javascript?

查看:24
本文介绍了如何将字符串转换为Javascript中的可执行代码行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

console.log("I am");

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

现在,我只想使用 x 来执行分配给它的代码字符串-例如,我什至不知道x的值,而只是想执行它-这可能吗?

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() This will convert string to javascript code.

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

这篇关于如何将字符串转换为Javascript中的可执行代码行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆