Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Object.keys([,1,,1]) different from Object.keys([,1,undefined,1])?

I was shocked that the result of

document.writeln(Object.keys([,1,,1]));

is

1,3

which filters the index of an array that doesn't contains anything automatically. But when I try to print out Object.keys([,1,undefined,1]):

document.writeln(Object.keys([,1,undefined,1]));

the result is:

1,2,3

which is different from the previous one, and I try to print the value of index 2 at the first one:

document.writeln([,1,,1][2]);

which is undefined actually. Why would Object.keys([,1,,1]) and Object.keys([,1,undefined,1]) return different results?

like image 757
ocomfd Avatar asked Feb 15 '26 12:02

ocomfd


1 Answers

In Object.keys([, 1, undefined, 1]) case, you are explicitly defining the third element to be undefined, but in Object.keys([, 1, , 1]), there is no element associated with the index 2. So, 2 is recognized as an array index in the first case, but not in the second case.

Just to represent the holes in the array, when you actually reference it, undefined is returned. That is why [, 1, , 1][2] is undefined.

like image 100
thefourtheye Avatar answered Feb 17 '26 01:02

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!