Ryan Griggs Ryan Griggs - 1 month ago 6
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)
{
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...

Answer

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.

Comments