Can a member function be added to the Array class in JavaScript without showing up in a for-in loop?

107 Views Asked by At

In some code I'm working on I created a JavaScript function that is applied solely to Arrays, and I thought I'd try adding it as a member function.

I added it like so:

Array.prototype.myfunc = function(a){
    ...
}

Which works fine for the most part. The problem I run into then is with a for-in loop. It includes that function in the loop. If I then type in this snippet:

var bar, foo = ['alpha', 'bravo', 'charlie'];
for(bar in foo) console.log(foo[bar]);

Then the output is along the lines of:

alpha
bravo
charlie
function myFunc(a){
    ...
}

So is there any way of doing this but avoiding it showing in the for-in loop?

1

There are 1 best solutions below

2
superluminary On

You can use Object.defineProperty to create non-enumerable attributes of any object, including arrays. Remember in JavaScript, arrays are just objects with numbers for keys, which is why attributes you add to them come up in a forEach.