Javascript array with index Number.MAX_VALUE

Can someone explain this behavior of javascript arrays

//create an empty array
var arr=[];

//added an entry with index Number.MAX_VALUE
arr[Number.MAX_VALUE]="test"

//On printing the array, its showing as empty
arr
//[]

//even its length=0
arr.length
//0

//on accessing the same value its showing the correct value
arr[Number.MAX_VALUE]
//"test"

I tried this with Number.MIN_VALUE.

Does anyone know the reason for this?

+4
source share
2 answers

Number.MAX_VALUEis not a valid array index. According to specification:

An integer index is the key of the String-value property, which is a canonical numeric string (see 7.1.16) and whose numeric value is +0 or a positive integer ≤ 2 53 -1. The array index is an integer index whose numerical value is in the range +0 ≤ i <2 32 & minus ;. 1

, , , ( , ):

var a = {};
a.prop = 'foo';
a[2 ** 32 - 2] = 'bar';
a[Number.MAX_VALUE] = 'baz';
console.log(Object.keys(a));
// ["4294967294", "prop", "1.7976931348623157e+308"]
+7

Number.MAX_VALUE , .

P ( value) , ToString (ToUint32 (P)) P ToUint32 (P) (2 ^ 32) -1

(http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%201st%20edition,%20June%201997.pdf 65, 15.4)

-1

Source: https://habr.com/ru/post/1672082/


All Articles