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


当前回答

在谷歌Chrome内置javascript,你可以去大约2^1024之前的数字被称为无穷大。

其他回答

在JavaScript中,有一个数字叫做Infinity。

例子:

(Infinity>100)
=> true

// Also worth noting
Infinity - 1 == Infinity
=> true

Math.pow(2,1024) === Infinity
=> true

对于这个主题的一些问题,这可能已经足够了。

为了安全

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);
}());

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

让我们来看看源头

描述

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.

浏览器兼容性

在谷歌Chrome内置javascript,你可以去大约2^1024之前的数字被称为无穷大。