Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array iteration using for..in with MooTools included

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);
});
like image 312
Anurag Avatar asked Dec 08 '22 04:12

Anurag


1 Answers

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 ...
});
like image 161
K Prime Avatar answered Mar 27 '23 12:03

K Prime