I'm new at JavaScript and there is one thing that bothers me. I have got a very simple code:
var a = [];
a[1] = 1;
i = typeof(a[0]);
index = a.indexOf(undefined);
len = a.length;
console.log(a);
console.log("\n" + len);
console.log("\n" + i);
console.log("\n" + index);
My question is: Why indexOf returns -1, instead of 0. I know that this method compare by ===, but I used as a parameter keyword undefined. If I change method parameter to "undefined" it also doesn't work (but this for me it's obvious). Can someone explain me this and tell what is the simpliest way to find undefined value in array?
This will in fact find an undefined
value in an array, the problem is that your array a
doesn't have any undefined
values in it, so it returns -1 meaning it did not find any. Your array looks like:
[*uninitialized*, 1]
The fact that you put nothing in the first position doesn't mean it's populated with an undefined
, it simply is not initialized/does not exist.
If you did something like:
var a = [undefined, 1];
var index = a.indexOf(undefined);
console.log(index);
It will in fact print 0
as expected.
Edit: to answer your question of how to find an uninitialized value, do the following
var a = [];
a[1] = 1;
for(var i = 0; i < a.length; i++){
if(a[i] === undefined){
console.log(i);
}
}
This will print the index of uninitialized array values. The reason this actually works unlike indexOf
is that a[i]
will evaluate to undefined
if:
(1) The element exists and it has the value undefined
, or
(2) The element doesn't exist at all. indexOf
however will skip these "gaps" in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With