简体   繁体   English

为什么 Nashorn 添加两个 integer 会产生双倍?

[英]Why Nashorn adds two integer produces double?

I am using java nashorn to evaluate javascript, some behavior related to numbers confuses me.我正在使用 java nashorn 来评估 javascript,一些与数字相关的行为让我感到困惑。

ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
Object result = nashorn.eval("3 + 3");

this gives 6 with type java.lang.Integer ,这给出了6类型为java.lang.Integer

but

ScriptEngine nashorn = new ScriptEngineManager().getEngineByName("nashorn");
nashorn.put(three, 3);
Object result = nashorn.eval("three + 3");

This gives 6.0 with type java.lang.Double .这给出了类型为java.lang.Double6.0

why is this happening?为什么会这样?

I am expecting, with nashorn.put(three, 3) should give 6 , nashorn.put(three, 3.0) should give 6.0 , is it possible?我期待, nashorn.put(three, 3)应该给6nashorn.put(three, 3.0)应该给6.0 ,这可能吗? any idea?任何想法?

My guess is that nashorn first compiles an expression to byte code or some intermediate code, then evaluates it.我的猜测是 nashorn 首先将表达式编译为字节码或一些中间代码,然后对其进行评估。 The compiler can evaluate the first expression because all values are literal whereas the second is evaluated at run time.编译器可以计算第一个表达式,因为所有值都是文字,而第二个是在运行时计算的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM