Question

I'm trying to use the 'arguments' variable available to a function in order to enumerate the arguments passed to a function, in Javascript, using :

for (var i in arguments){
   ...
}

This seems to be working for me in the chrome and firebug consoles, while does not work with Rhino. With the former two, I can successfully enter the for loop and see the arguments, while with the latter, it doesn't seem like the for loop is even entered.

Why is this happening and how can I prevent this ?

Was it helpful?

Solution

From Javascript for..in looping over arguments ie.for( arg in arguments) does not work in IE8 but it works in Chrome 8 :

First of all, while the arguments object available within a function is not an array, it is "array-like" enough such that an incremental for loop (for (var i = 0, len = arguments.length; i < len; i++) { ... }) is preferable - not only because it runs faster, but also because it avoids other pitfalls - one of which is exactly what you're falling into.

To actually answer the question of why the second loop doesn't work, it's important to realize just what for ... in loop does: it iterates through all enumerable properties found in an object. Now, I've bolded 2 words in that statement, because I used these two words purposefully to indicate a couple of nuances that, while they may seem subtle, can drastically affect the behavior of your code if you don't realize what's going on.

First let's focus on all - by which I mean to say, not just properties of the object itself, but also potentially properties said object has inherited from its prototype, or its prototype's prototype, or so on. For this reason, it is very often recommended that you "guard" any for ... in loop by immediately additionally qualifying it with the condition if (obj.hasOwnProperty(p)) (assuming your loop were written for (var p in obj)).

But that's not what you're running into here. For that, let's focus on that second word, enumerable. All properties of objects in JavaScript are either enumerable or non-enumerable, which pretty much directly relates to whether the property shows up in a for ... in loop or not. In browsers such as Firefox and IE, as it turns out, the arguments object's numeric properties are not enumerable (nor is its length as it were), which is precisely why you're not iterating through anything!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top