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


当前回答

我用一个公式做了一个简单的测试,X-(X+1)=-1,我在Safari、Opera和Firefox(在OS X上测试)上可以得到的X的最大值是9e15。下面是我用于测试的代码:

javascript: alert(9e15-(9e15+1));

其他回答

我这样写:

var max_int = 0x20000000000000;
var min_int = -0x20000000000000;
(max_int + 1) === 0x20000000000000;  //true
(max_int - 1) < 0x20000000000000;    //true

int32也是一样

var max_int32 =  0x80000000;
var min_int32 = -0x80000000;

简短的回答是“视情况而定。”

如果你在任何地方使用位操作符(或者如果你引用数组的长度),范围是:

无符号:0…(1 > > > 0)

签名:(-(1 > > > 1)1)……(1 > > > 1)

(恰巧按位操作符和数组的最大长度被限制为32位整数。)

如果你不使用位操作符或使用数组长度:

签名:(-Math pow (2.53)) ... + Math . pow (2.53))

这些限制是由“Number”类型的内部表示施加的,通常对应于IEEE 754双精度浮点表示。(请注意,与典型的有符号整数不同,由于内部表示的特征,负极限的大小与正极限的大小相同,它实际上包括一个负0!)

让我们来看看源头

描述

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.

浏览器兼容性

我用一个公式做了一个简单的测试,X-(X+1)=-1,我在Safari、Opera和Firefox(在OS X上测试)上可以得到的X的最大值是9e15。下面是我用于测试的代码:

javascript: alert(9e15-(9e15+1));

在JavaScript中,数字的表示是2^53 - 1。

然而,按位操作是在32位(4个字节)上计算的,这意味着如果你超过32位移位,你将开始丢失位。