Javascript array iteration using for..in with MooT

2019-02-23 07:49发布

问题:

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);
});

回答1:

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.



回答2:

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 ...
});