来自Java的Rhino JS / ScriptEngine – 整数输入,翻倍?

我正在尝试使用Java来嵌入Javascript.我注意到当我评估一个在Javascript中一起添加两个int的脚本时,结果会以Double形式返回.

ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
engine.put("x", 3);
engine.put("y", 4);

assertEquals(3, engine.eval("x")); // OK
assertEquals(4, engine.eval("y")); // OK
assertEquals(7, engine.eval("x + y")); // FAILS, actual = (Double) 7.0

那么为什么x y表达式返回double而不是int?

Javascript本身正在做一些我不明白的类型推广吗?

解决方法:

有趣的事实:javascript(ECMAScript)中的所有数字都是双精度的.

The Number type has exactly 18437736874454810627 (that is, 264−253+3)
values, representing the double-precision 64-bit format IEEE 754
values as specified in the IEEE Standard for Binary Floating-Point
Arithmetic, except that the 9007199254740990 (that is, 253−2) distinct
“Not-a-Number” values of the IEEE Standard are represented in
ECMAScript as a single special NaN value.

http://people.mozilla.org/~jorendorff/es6-draft.html#sec-8.1.5

上一篇:Web——day04——css2D


下一篇:javascript – 完整性检查:Rhino没有require函数,对吧?