What's the fastest way to iterate over an object's properties in Javascript?

后端 未结 8 1692
旧巷少年郎
旧巷少年郎 2020-12-13 00:25

I know that I can iterate over an object\'s properties like this:

for (property in object)
{
    // do stuff
}

I also know that the fastest

8条回答
  •  萌比男神i
    2020-12-13 00:48

    Explicit use of Iterator in JavaScript 1.7+ might be faster or slower. Of course this will only iterate an object's own properties. The catch statement also might be faster with ex instanceof StopIteration replaced with ex === StopIteration.

    var obj = {a:1,b:2,c:3,d:4,e:5,f:6},
       iter = new Iterator(obj, true);
    
    while (true) {
        try {
            doSomethingWithProperty(iter.next());
        } catch (ex if (ex instanceof StopIteration)) {
            break;
        }
    }
    

提交回复
热议问题