I'm relatively new to Javascript and all of its infinite greatness. I wanted to practice defining my own functions for object prototypes, so I practiced writing a contains()
function for Array
:
if (!Array.prototype.contains){
Array.prototype.contains = function(target){
for (var i in this){
console.log(i);
if (this[i] == target) return true;
}
return false;
}
}
Essentially, contains() iterates through each element inside this
to look for the target
. However, I'm noticing that console.log(i)
returns the index number (ie. 0
, 1
, 2
, etc.) as expected depending on the number of elements inside the array. However, it also always prints out contains
! Here's the output from my console.log
with only one element in the array:
0
contains
However, if I change the way I iterate the for
loop, I don't get the contains
output:
if (!Array.prototype.contains){
Array.prototype.contains = function(target){
for (var i = 0; i < this.length; i++){
console.log(i);
if (this[i] == target) return true;
}
return false;
}
}
Output:
0
Now I've read through this StackOverflow post explaining the dangers of using for... in
with array iteration, but I'm at a loss to explain programmatically why contains
is appear in my first code snippet. If I console.log(this)
on my Firefox developer console, I receive as expected, an Array object:
Array [ "scrubBackButton2", "scrubNextButton1" ]
Is the last element of an array object always the name of the function being called with?
I'm learning JS mostly through trial and error, so please definitely do refer me to a good piece of documentation or prior SO post if I've somehow missed a good answer to this!