Ryan Griggs Ryan Griggs - 1 year ago 88
Javascript Question

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)

And you get:


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...

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download