First of all, although the arguments object, accessible within the function, is not an array, it is rather "similar to an array", which is preferable to the increment for the loop ( for (var i = 0, len = arguments.length; i < len; i++) { ... } ) - not only because it works faster, but also because it avoids other traps - one of which is exactly what you fall into.
To answer the question of why the second loop does not work, it is important to understand what exactly ... in the loop: it iterates through all the listed properties found in the object. Now I have highlighted 2 words in this statement because I used these two words purposefully to indicate a couple of nuances that, although they may seem subtle, can dramatically affect the behavior of your code if you do not understand what is happening.
First, let's focus on everything that I have in mind, not only the properties of the object itself, but also potentially the properties that this object inherited from its prototype or prototype prototype or so on. For this reason, it is often recommended that you "guard" any of ... in the loop, adding in addition its qualifications with the condition if (obj.hasOwnProperty(p)) (assuming your loop was written for (var p in obj) )
But that is not what you are doing here. To do this, let me focus on this second word enumerable . All object properties in JavaScript are enumerable or not enumerated, which is largely directly related to whether the property appears in the for for ... in loop or not. As it turned out, in browsers such as Firefox and IE, the numeric properties of the arguments object are not listed (nor its length ), which is why you are not iterating through anything!
But in fact, in the end, to iterate through everything that is an array or an array, you better use an incremental loop (as M. Kolodny pointed out) and generally avoid these frauds (not to mention the potential of cross-browser inconsistencies - I seem to notice that in Chrome 10 the numeric properties of arguments objects are listed!)
Ken franqueiro
source share