Ryan Griggs
Ryan Griggs

Reputation: 2758

Javascript Array.remove() by John Resig - why does it enumerate in for-in statement?

I just found John Resig's Array.remove() function. [Looks like his site isn't properly parsing the bb-code so it's hard to read!]

While it's nifty, the problem is that the 'remove()' method enumerates in a for-in statement for every array after loading his code.

For example, after prepending his code, do this:

var a = ["a", "b", "c"];
for (i in a)
{
    console.log(i);
}

And you get:

0
1
2
remove

Why don't all the other built-in properties and methods of the Array object enumerate, and is there any way to prevent this happening for the remove() method?

Here's a jsfiddle...

Upvotes: 1

Views: 84

Answers (1)

Pointy
Pointy

Reputation: 413826

You can use Object.defineProperty() to add the method:

Object.defineProperty(Array.prototype, "remove", {
  value: function() { ... }
});

That will by default leave the "enumerable" flag turned off for the property, meaning that it won't show up in for ... in loops.

Upvotes: 2

Related Questions