Reputation: 4020
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?
Upvotes: 3
Views: 88
Reputation: 2113
You're right to think that it doesn't make much sense. It doesn't. Basically, in javascript there is sometimes a difference between "undefined" and "has never been defined". In the first example, you're not giving the second index any value, so it doesn't print. In the second example, you're giving it a value (even though that value is undefined, it's still getting a value) so it prints it.
Upvotes: 0
Reputation: 23149
This is one caveat to be careful with Javascript arrays : you can have sparse arrays, arrays with missing values, which is not the same as having undefined
values (the array element exists, like a variable can be declared, but it's value is `undefined).
Note that you can get the same behavior using delete
on an array element.
As already said, you can test for empty value wiht === undefined
, which is even more confusing, because it does not usually cause the same output.
Upvotes: 0
Reputation: 239463
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
.
Upvotes: 3