/    Sign up×
Community /Pin to ProfileBookmark

Modifying array prototype – inArray with for .. in

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”;[/CODE]

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 />”;
}[/CODE]

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”);[/CODE]

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;
};[/CODE]

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.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@mrhooMar 19.2008 — User defined methods are always enumerable.

You can't mark them not-enumerable in javascript.

So you have to screen out prototype properties-

[CODE]var A= [];
for(var p in obj){
if(obj.prototype[p]!==obj[p]){
A.push(p+'='+obj[p]);
}
}
alert(A.join('n'));[/CODE]
Copy linkTweet thisAlerts:
@CarthauthorMar 19.2008 — Thanks. ?
×

Success!

Help @Carth spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...