Question

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);
});
Was it helpful?

Solution

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.

OTHER TIPS

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 ...
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top