在 Nashorn 中区分 null 和 undefined 值

Differ null and undefined values in Nashorn

我是运行这个代码

ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("var out;");
engine.eval("var out1 = null;");
Object m = engine.get("out");
Object m1 = engine.get("out1");

并得到 m == null 和 m1 == null。

如何判断value是undefined还是null?

Java 没有 "undefined" 的概念,因此理解区别需要用脚本的语言来表达。我建议使用这个表达式:

Boolean isUndefined = engine.eval("out === undefined");

我会检查

engine.eval("typeof out") 

这将是 "undefined" 和

engine.eval("typeof out1") 

将是 "object"

实际上,了解脚本返回的对象是否为 undefined 的正确方法是询问 ScriptObjectMirror:

import jdk.nashorn.api.scripting.ScriptObjectMirror;

Object m = engine.get("out");

if (ScriptObjectMirror.isUndefined(m)) {
    System.out.println("m is undefined");
}    

替代方法,使用 Nashorn 内部 API

您也可以通过检查其类型来完成:

import jdk.nashorn.internal.runtime.Undefined;

Object m = engine.get("out");

if (m instanceof Undefined) {
    System.out.println("m is undefined");
}

请注意 Nashorn 没有将 Undefined 类型作为 public API 的一部分,因此使用它可能会有问题(他们可以在不同版本之间自由更改),所以使用 ScriptObjectMirror 代替。只是出于好奇在这里添加了这个...