Integer overflow to negative number

According to this link, I found out that in IE8 the index of the new element will be a negative number if the array was created with an index greater than 2147483647.

And there is this example:

function test() { 
    var arr = new Array();         
    arr[2147483650] = 10000; 
    arr.push(10);     
    document.write(arr["-2147483645"] == 10); 
} 
test();

I don’t understand why the new element of the array has an index -2147483645, I understand the negative part, I just don’t know how to find out what the new index is 2147483645, -2147483644or -2147483651...

+4
source share
2 answers

When representing a number in 32 bits, the most significant bit is used as a sign bit, so when representing a number, for example, 2147483647 in binary format, this

01111...111

where there are 31 1. When we add one more, we get

10000...000

31 0. , , . - 0 , -0 2147483648 ( 2147483647, 0, , , , "" ).

, , ,

1000...00 = -2147483648 // this is 2147483648
1000...01 = -2147483647 // this is 2147483649
1000...10 = -2147483646 // this is 2147483650

.. , 2147483650 -2147483646, , , , -2147483645.

. .

+3

, -2147483645 , , :

function test() { 
    var arr = new Array();         
    arr[2147483650] = 10000; 
    arr.push(10);     
    console.log(arr["-2147483645"] == 10); 
    console.log(arr)
} 
test();

// false
// [2147483650: 10000, 2147483651: 10]

, -2147483645

, JavaScript . Array - . -2147483645, . , , .

var arr = [];
arr[2147483650] = 'foo';

// The index is really just converted to a string behind the scenes
console.log(arr[2147483650] === arr["2147483650"]);

// true

, , .

var arr = [];
arr[0] = 'foo';
console.log(arr);
// ["foo"]
// Has the array notation

var arr = [];
arr[2147483650] = 'bar';
console.log(arr);
// [2147483650: "bar"]
// Notice the object notation?
+3

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


All Articles