1 回答

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
問題的根本原因是 Javascript 的print()函數(shù)沒有返回值(在 TypeScript 中則返回值function print(): void)。因此,您的代碼工作得很好(您實(shí)際上可以看到2在標(biāo)準(zhǔn)輸出中打?。浞祷刂祊rint(2);被void解釋為null.
如果您調(diào)用返回值的函數(shù)(或語(yǔ)句),它將正常工作:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "x = 1+2;";
Object s = engine.eval(foo);
System.out.println(s); // printing 3
您還可以使用變量來處理結(jié)果:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String jsCode = "jsVar = 1+2;";
engine.eval(jsCode);
Object javaVar = engine.get("jsVar");
System.out.println(javaVar); // printing 3
添加回答
舉報(bào)