我有下面的代码,
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Test {
public static void main(String[] args) throws Exception {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
Test ctrl = new Test();
String[] arr = {"1==1"};
String eer = "1==1";
engine.put("hi", ctrl);
System.out.println(engine.eval(arr[0])); //true
System.out.println(engine.eval(eer)); //true
System.out.println(engine.eval("hi.values()")); //prints 1==1
}
public String values() {
return "1==1";
}
}
我可以理解最后一个 sout
语句用双引号引起来,因此它按原样打印值。
我怎样才能将表达式计算为 像其他字符串变量一样?
编辑
在java中如果我添加,
String result = ctrl.values(); //returns 1==1
System.out.println(engine.eval(result));//true
我在 javascript 上尝试了同样的方法
var result = myfun();
function myfun(){
return "1!=1";
}
if(result){
window.alert("yes"); // This came even when condition is false
}
最佳答案
How can i make the statement to evaluate the expression as like other string variables?
为什么不engine.eval()
两次?
System.out.println(engine.eval(engine.eval("hi.values()")));
In java if i add , [some code that does something] I tried same on javascript [some identical-looking code that does a different thing]
JavaScript 中没有对 eval
的隐式调用。这意味着 result
包含非空字符串 1!=1
,该字符串在 if- 中变为 true
声明。
关于java - 方法返回字符串与字符串变量之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38099775/