Differ null and undefined values in Nashorn

放肆的年华 提交于 2019-12-06 01:28:43

问题


I'm running this code

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");

And getting m == null and m1 == null.

How to determine if value is undefined or null?


回答1:


Java doesn't have a concept of "undefined", so understanding the distinction will require expressing it in the script's language. I suggest using this expression:

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



回答2:


Actually, the correct way to know if the Object returned by the script is undefined is by asking ScriptObjectMirror:

import jdk.nashorn.api.scripting.ScriptObjectMirror;

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

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

Alternative way, using Nashorn internal API

You can also do it by checking its type:

import jdk.nashorn.internal.runtime.Undefined;

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

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

Notice that Nashorn did not make the Undefined type part of the public API, so using it can be problematic (they are free to change this between releases), so use ScriptObjectMirror instead. Just added this here as a curiosity...




回答3:


I'd check

engine.eval("typeof out") 

which will be "undefined" and

engine.eval("typeof out1") 

would be "object"



来源:https://stackoverflow.com/questions/29277606/differ-null-and-undefined-values-in-nashorn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!