javascript 将字符串转换为表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14725498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting string to expression
提问by Payman Biukaghazadeh
Is there any way to convert a string to an expression?
有没有办法将字符串转换为表达式?
my string: var1 == null && var2 != 5
我的字符串: var1 == null && var2 != 5
I want to use this string as a condition of the if()
, Like if(var1 == null && var2 != 5)
我想用这个字符串作为if()
, Like的条件if(var1 == null && var2 != 5)
回答by 999k
Use eval
. This will do
使用eval
. 这会做
if (eval(" var1 == null && var2 != 5"))
{
}
回答by VisioN
One option is to create and call new Function
:
一种选择是创建并调用new Function
:
var strExpr = "var1 == null && var2 != 5";
if (new Function("return " + strExpr)()) {
// ...
}
回答by TomTom
To see how eval works, just write in console:
要查看 eval 的工作原理,只需在控制台中编写:
console.log(eval("1==1"));
console.log(eval("1==2"));
This will output true and false
这将输出真假
回答by Marc Fischer
1.) Java and Javascript don't have much in common, but the name and some syntax inherited from C.
1.) Java 和 Javascript 没有太多共同点,但名称和一些语法继承自 C。
2.) Anyhow, you generally should avoid what you are trying to do. In most languages and cases this practice should not be used due to security problems.
2.) 无论如何,您通常应该避免您尝试做的事情。在大多数语言和情况下,由于安全问题,不应使用这种做法。
回答by Giancarlo
The String() function converts the value of an object to a string, you can do eval(String)
String() 函数将对象的值转换为字符串,可以执行 eval(String)
<html>
<head>
<script>
function myFunction(){
var var1 = new String("999 888");
var var2 = "5";
var var3;
var var4 = 8;
document.write(String(var2)+ "<br>");
document.write(String(var4)+ "<br>");
//5
//8
if(var3 === undefined && var2 != 6){
alert('var1='+var1+' var2='+var2);
}
var ev=eval(String(var3 === undefined && var2 != 6));
alert(ev);
var ev1=eval("var3 === undefined && var2 != 6");
alert(ev1);
}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>
Try it and good luck!
试试吧,祝你好运!