Javascript array iteration using for..in with MooTools included

后端 未结 2 759
离开以前
离开以前 2021-01-19 09:35

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

相关标签:
2条回答
  • 2021-01-19 10:07

    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 ...
    });
    
    0 讨论(0)
  • 2021-01-19 10:20

    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.

    0 讨论(0)
提交回复
热议问题