Why should I use 'i in array' inside my own custom 'array.indexOf'?
-
27-10-2019 - |
Question
I have seen many times things like this:
function customArrayIndexOf(item, array){
for (var i = 0, l = array.length; i < l; i++) {
if (i in array && array[i] === item) return i;
}
return -1;
}
However, I am not sure why is the i in array
needed.
I have three questions:
- What it is doing?
- Is it necessary?
- When it will fail without it?
Solution
Sparse arrays may cause a false positive without the check:
var customArrayIndexOf = function(item, array){
for (var i = 0, l = array.length; i < l; i++) {
if (i in array && array[i] === item) return i;
}
return -1;
},
customArrayIndexOfNoCheck = function(item, array){
for (var i = 0, l = array.length; i < l; i++) {
if (array[i] === item) return i;
}
return -1;
};
var t=[]; t[1]=1;
customArrayIndexOfNoCheck(undefined, t); // 0
customArrayIndexOf(undefined, t); // -1
(i
and l
should be local, i.e. declared with var
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow