这是由语言定义的吗?有确定的最大值吗?在不同的浏览器中是否有所不同?
当前回答
让我们来看看源头
描述
The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991 or ~9 quadrillion). The reasoning behind that number is that JavaScript uses double-precision floating-point format numbers as specified in IEEE 754 and can only safely represent numbers between -(2^53 - 1) and 2^53 - 1. Safe in this context refers to the ability to represent integers exactly and to correctly compare them. For example, Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2 will evaluate to true, which is mathematically incorrect. See Number.isSafeInteger() for more information. Because MAX_SAFE_INTEGER is a static property of Number, you always use it as Number.MAX_SAFE_INTEGER, rather than as a property of a Number object you created.
浏览器兼容性
其他回答
ECMAScript 6:
Number.MAX_SAFE_INTEGER = Math.pow(2, 53)-1;
Number.MIN_SAFE_INTEGER = -Number.MAX_SAFE_INTEGER;
要用于位操作的任何值必须在0x80000000(-2147483648或-2^31)和0x7fffffff(2147483647或2^31 - 1)之间。
控制台会告诉您0x80000000等于+2147483648,但是0x80000000 & 0x80000000等于-2147483648。
JavaScript在ECMAScript 2020中收到了一个新的数据类型:BigInt。它引入了带有“n”后缀的数值字面量,并允许任意精度:
var a = 123456789012345678901012345678901n;
当然,当这样大的整数(可能是无意的)被强制转换为数字数据类型时,精度仍然会丢失。
而且,很明显,由于有限的内存,总是会有精度限制,为了分配必要的内存和对如此大的数字执行算术,在时间方面会有成本。
例如,生成一个具有10万个十进制数字的数字,在完成之前会有明显的延迟:
console.log(BigInt("1".padEnd(100000,"0")) + 1n)
...但它确实有效。
>= ES6:
Number.MIN_SAFE_INTEGER;
Number.MAX_SAFE_INTEGER;
< = ES5
参考文献:
Number.MAX_VALUE;
Number.MIN_VALUE;
console.log (MIN_VALUE, Number.MIN_VALUE); console.log (MAX_VALUE, Number.MAX_VALUE); console.log (MIN_SAFE_INTEGER, Number.MIN_SAFE_INTEGER);/ / ES6 console.log (MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);/ / ES6
为了安全
var MAX_INT = 4294967295;
推理
我认为我应该聪明一点,用更实用的方法找到x + 1 === x的值。
我的机器每秒只能计算1000万次左右……所以我会在28.56年后给出确切的答案。
如果你等不了那么久,我敢打赌
大多数循环都不会持续28.56年 9007199254740992 ===数学。Pow(2,53) + 1是足够的证明 您应该坚持使用4294967295,即Math.pow(2,32) - 1,以避免预期的位移位问题
求x + 1 === x:
(function () {
"use strict";
var x = 0
, start = new Date().valueOf()
;
while (x + 1 != x) {
if (!(x % 10000000)) {
console.log(x);
}
x += 1
}
console.log(x, new Date().valueOf() - start);
}());