Javascript array iteration using for..in with MooTools included

后端 未结 2 780
离开以前
离开以前 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 ...
    });
    

提交回复
热议问题