我有這個Java訪問類的實例在JavaScript程序犀牛:Java的數字不循規蹈矩如Javascript數字
public class ContentProvider {
public Object c(int n) {
switch (n) {
case 1: return 1.1;
case 2: return 2.2;
case 3: return 3.3;
case 4: return "4";
case 5: return new java.util.Date();
}
return null;
}
}
這裏面的代碼的main():
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
engine.put("ctx", new ContentProvider());
res = engine.eval("ctx.c(1)");
System.out.printf("rhino:> %s (%s)%n"
, res
, res != null ? res.getClass().getName() : null
);
簡單的表達ctx.c(1)
打印:
rhino:> 1.1 (java.lang.Double)
現在這裏是ctx.c(1) + ctx.c(2)
會發生什麼:
rhino:> 1.12.2 (java.lang.String)
最後(ctx.c(1) + ctx.c(2)) * ctx.c(3)
:
rhino:> nan (java.lang.Double)
Rhino是不是執行數算術的字符串連接!下面的程序按預期工作,而不是:
engine.put("a", 1.1);
engine.put("b", 2.2);
engine.put("c", 3.3);
res = engine.eval("(a + b) * c");
輸出:
rhino:> 10,89 (java.lang.Double)
哦,我的上帝,有人實際使用的「Java」和「JavaScript的」標籤一起* *正確! – immibis
但爲什麼不嘗試'engine.eval(「typeof ctx.c(1)」)'並查看JavaScript認爲該類型是什麼? – immibis
typeof ctx.c(1)=對象 – lunicon