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

后端 未结 8 1687
旧巷少年郎
旧巷少年郎 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条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-13 00:58

    The for/in loop is the best way to enumerate properties of a Javascript object. It should be understood that this will only loop through "enumerable" properties, and in no particular order. Not all properties are enumerable. All properties/methods added programmatically via your own Javascript code will be enumerable, but predefined properties/methods that are inherited (such as toString) are not usually enumerable.

    You can check enumerability like so...

    var o = new Object();
    alert(o.propertyIsEnumerable("toString"));
    

提交回复
热议问题