Number.isSafeInteger() 方法用来判断传入的参数值是否是一个“安全整数”(safe integer)。
一个安全整数是一个符合下面条件的整数:
- 可以准确地表示为一个IEEE-754双精度数字,
- 其IEEE-754表示不能是舍入任何其他整数以适应IEEE-754表示的结果。.
比如,253 - 1 是一个安全整数,它能被精确表示,在任何 IEEE-754 舍入模式(rounding mode)下,没有其他整数舍入结果为该整数。作为对比,253 就不是一个安全整数,它能够使用 IEEE-754 表示,但是 253 + 1 不能使用 IEEE-754 直接表示,在就近舍入(round-to-nearest)和向零舍入中,会被舍入为 253。
安全整数范围为 -(253 - 1)到 253 - 1 之间的整数,包含 -(253 - 1)和 253 - 1。
语法
Number.isSafeInteger(testValue)
参数
-
testValue - 需要检测的参数。
返回值
一个布尔值 表示给定的值是否是一个安全整数(safe integer)。
示例
Number.isSafeInteger(3); // true
Number.isSafeInteger(Math.pow(2, 53)) // false
Number.isSafeInteger(Math.pow(2, 53) - 1) // true
Number.isSafeInteger(NaN); // false
Number.isSafeInteger(Infinity); // false
Number.isSafeInteger("3"); // false
Number.isSafeInteger(3.1); // false
Number.isSafeInteger(3.0); // true
Polyfill
Number.isSafeInteger = Number.isSafeInteger || function (value) {
return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
};
规范
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Number.isSafeInteger |
Standard | Initial definition. |
| ECMAScript Latest Draft (ECMA-262) Number.isSafeInteger |
Draft |
浏览器兼容性
Update compatibility data on GitHub
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
isSafeInteger |
Chrome Full support 34 | Edge Full support 12 | Firefox Full support 32 | IE No support No | Opera Full support 21 | Safari Full support 10 | WebView Android Full support ≤37 | Chrome Android Full support 34 | Firefox Android Full support 32 | Opera Android Full support 21 | Safari iOS Full support Yes | Samsung Internet Android Full support 2.0 | nodejs Full support 0.12 |
Legend
- Full support
- Full support
- No support
- No support