有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaScriptRhinoJS/ScriptEngine从Java整数输入,加倍输出?

我正在尝试Rhino在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本身是否在做一些我不理解的类型提升


共 (2) 个答案

  1. # 1 楼答案

    JavaScript只有一个数字类型-Number,它类似于JavaDouble类型。我期望引擎强制类型Number来执行该算法

  2. # 2 楼答案

    有趣的事实: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