这是由语言定义的吗?有确定的最大值吗?在不同的浏览器中是否有所不同?


当前回答

其他人可能已经给出了一般的答案,但我认为给出一个快速确定它的方法会是一个好主意:

for (var x = 2; x + 1 !== x; x *= 2);
console.log(x);

这给了我9007199254740992在Chrome 30不到一毫秒。

它将测试2的幂,以找出当“加”1时,哪一个等于他自己。

其他回答

253 == 9 007 199 254 740 992。这是因为数字存储为52位尾数中的浮点数。

最小值为-253。

这使得一些有趣的事情发生了

Math.pow(2, 53) == Math.pow(2, 53) + 1
>> true

也可能是危险的:)

var MAX_INT = Math.pow(2, 53); // 9 007 199 254 740 992
for (var i = MAX_INT; i < MAX_INT + 2; ++i) {
    // infinite loop
}

进一步阅读:http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html

Jimmy的答案正确地表示了连续的JavaScript整数谱,从-9007199254740992到9007199254740992,包括(对不起,9007199254740993,您可能认为您是9007199254740993,但您错了! 下面或jsfiddle中的演示)。

console.log(9007199254740993);

然而,没有答案可以通过编程来发现/证明这一点(除了CoolAJ86在他的回答中提到的将在28.56年完成的答案),所以这里有一个稍微更有效的方法来做到这一点(准确地说,它更有效约28.559999999968312年:),以及一个测试小提琴:

/** * Checks if adding/subtracting one to/from a number yields the correct result. * * @param number The number to test * @return true if you can add/subtract 1, false otherwise. */ var canAddSubtractOneFromNumber = function(number) { var numMinusOne = number - 1; var numPlusOne = number + 1; return ((number - numMinusOne) === 1) && ((number - numPlusOne) === -1); } //Find the highest number var highestNumber = 3; //Start with an integer 1 or higher //Get a number higher than the valid integer range while (canAddSubtractOneFromNumber(highestNumber)) { highestNumber *= 2; } //Find the lowest number you can't add/subtract 1 from var numToSubtract = highestNumber / 4; while (numToSubtract >= 1) { while (!canAddSubtractOneFromNumber(highestNumber - numToSubtract)) { highestNumber = highestNumber - numToSubtract; } numToSubtract /= 2; } //And there was much rejoicing. Yay. console.log('HighestNumber = ' + highestNumber);

其他人可能已经给出了一般的答案,但我认为给出一个快速确定它的方法会是一个好主意:

for (var x = 2; x + 1 !== x; x *= 2);
console.log(x);

这给了我9007199254740992在Chrome 30不到一毫秒。

它将测试2的幂,以找出当“加”1时,哪一个等于他自己。

让我们来看看源头

描述

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;