I have an associative array of strings, with the keys as strings, like this:
[CODE]var theArray = new Array();
theArray[“test1″]=”test number 1”;
theArray[“test2″]=”test number 2”;
theArray[“test3″]=”test number 3”;
I use this array in foreach which I believe looks like this in Javascript:
[CODE]for (var element in theArray) {
document.body.innerHTML=document.body.innerHTML+element+”<br />”;
}
This outputs the keys of my array, i.e. test1, test2, test3. Which is what it should do I believe.
I then have another array which contains some of these string values:
[CODE]var testArray = new Array(“test number 1″,”test number 4”);
And I intended to test whether a string was in this array or not.
But I discovered Javascript has no built in inArray method. So I defined my own like this:
[CODE]Array.prototype.inArray = function(value) {
for (var i=0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
But now when I loop through the array with for (.. in ..) it is returning inArray as a 4th key. Why? I instead have to define inArray as a function that takes the array and the search value as arguments. By extending the Array prototype it’s adding a key to every array I create before or after? The value of the inArray key is the function in its entirety as I typed it.
Am I doing something wrong here? Looking at it, maybe it’s intended to do this, but I wanted to check I’m not misunderstanding.