How To Exclude Added To Array Methods From Processing In "for..in" Loop? (javascript)
Solution 1:
You should never use for..in loops to iterate over array elements. for..in is designed for iterating over properties, and should only be used for that, for exactly the reason you've just described. Many libraries modify array, date, etc prototypes, so you should not rely on for..in iterating just the array elements. Use the for(;;) method, it's guaranteed to do what you want. And it's no faster than a for..in loop, because it's native to javascript as well.
For more info, read about it in the prototype.js library.
Solution 2:
Yes, but it's JavaScript 1.7+ - only. Opera only has limited JavaScript 1.7 support, which includes very basic support of destructuring assignment so this won't work in Opera but it will work in Firefox.
This implementation allows safely using for [each](item in array)
:
Array.prototype.__iterator__ = function (flag) {
var len = this.length, i = 0;
for (; i < len; i++) {
yield flag ? i : this[i];
}
};
Solution 3:
As others stated, you should NOT use for..in to iterate over arrays. It is slower than using a for(;;).
You should also cache the length of the array if you are concerned with performance, as:
for (var i=0, len=arr.length; i<len; i++)
{
...
}
Use only for..in to iterate over properties of objects. To exclude the inherited properties, use the hasOwnProperty() method:
for (var prop inobject)
{
// Don't include properties inherited from the prototype chainif (object.hasOwnProperty(prop))
{
...
}
}
Solution 4:
There is another option now with ES5 support, it lets you define non-enumerable properties! It should be possible (though I haven't tested) to do something like this:
Object.defineProperty( Array.prototype, "myNewMethod", {
value: function(){},
writable: true,
enumerable: false, /* this controls for..in visibility */configurable: true
});
Solution 5:
What you're describing is exactly why you use
for (var i=0; i<arr.length; i++) { ... }
instead of:
for (var item in arr) { ... }
because they are different.
If you don't want all the members that you'll get in the second form and just the indexed elements then use the first form.
Post a Comment for "How To Exclude Added To Array Methods From Processing In "for..in" Loop? (javascript)"