views:

611

answers:

2

I am iterating over an array in MooTools but seeing additional items when iterating through the array using the shorthand for..in loop. It works fine when I use the regular for loop. Is this a problem with MooTools polluting the global namespace or am I doing something wrong here?

There is a createTabs() function that iterates over an array and creates a tab for each value in the array:

function createTabs() {
    var myTabs = [["First", "a.png"], ["Second", "b.png"]];
    for(var i in myTabs) {
        var tab = new Tab(myTabs[i][0], myTabs[i][1]);
        console.log(i);
    }
}

This is the output of console.log(i):

0
1
$family
each
clean
associate
link
contains
extend
getLast
getRandom
include
combine
erase
empty
flatten
hexToRgb
rgbToHex
toJSON

I understand the first 2 indexes, but where is the rest coming from?

Edit: Thanks for the quick answers Chetan and k Prime. That makes sense, and the Array.each addition by MooTools is much cleaner way to iterate!

Looks a lot better now:

myTabs.each(function(item) {
    var tab = new Tab(item[0], item[1]);
    console.log(item);
});
+3  A: 

for..in is not meant for array iteration. It iterates over all the properties of an object that are not built-in. Since MooTools has added more functions to Array prototype, they are now array properties as well. See this https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/For...in

Just use a basic for loop for array iteration.

Chetan Sastry
+4  A: 

As Chetan pointed out, for .. in is meant for object property iteration, not arrays. however, you can iterate over the current members (and not the inherited members set by MooTools), by using hasOwnProprty, like so:

for (i in array)
    if (array.hasOwnProperty(i))
    {
        //.. do stuff ...
    }

Orr, better still, since you're using MooTools, just use the Array.each method:

array.each (function (item, index)
{
    // ... do stuff ...
});
K Prime
thanks k Prime, array.each makes life a lot easier
Anurag
It should be pointed out that function based iteration (e.g.: `array.each`) is much slower than a normal `for` or `for..in`
Justin Johnson
just a note that .each will be a standard browser feature soon as per ECMA and mootools checks if there is native support upon defining the alias for the function-based forEach to .each - hence the performance drop is only temporary and would mainly affect older browsers. i still would not recommend using for ... in for array walking unless you need the array keys (but it's still a hack)
Dimitar Christoff