问题
I need to evaluate this function in Javascript from Scala/Java
function hello(a, b) {
return a+b;
}
I did this basic code:
val factory = new ScriptEngineManager(null)
val engine = factory.getEngineByName("JavaScript")
val body =
"""
|function hello(a, b) {
| return a+b;
|}
""".stripMargin
engine match {
case engine: Invocable =>
engine.eval(body)
println(engine.invokeFunction("hello", null, 1: java.lang.Double))
}
For the parameter a I'm passing a null and I get a 1.0 as a result. If I hack my javascript (I DON'T WONT TO DO THIS) and I make it:
function hello(a, b) {
if (a === null) {
a = undefined;
}
return a+b;
}
I get the expected NaN.
The correct solution would be passing an undefined to the invokeFunction: How do I do this?
回答1:
ScriptEngine.eval translates undefined to null - as there is no concept of undefined in Java. If you do want to get internal nashorn undefined object and pass it around (why?), you can do something like this:
import javax.script.*;
public class Test {
private static Object undefined;
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
e.eval("Packages.Test.setUndefined(undefined)");
e.eval("function func(a, b) { return a + b; }");
Object val = ((Invocable)e).invokeFunction("func", undefined, 44);
if (val instanceof Double && ((Double)val).isNaN()) {
System.out.println("got NaN as expected");
}
}
public static void setUndefined(Object obj) {
undefined = obj;
}
}
来源:https://stackoverflow.com/questions/30528083/passing-undefined-to-nashorn-javascript-in-scala-java