简体   繁体   中英

Internally how does JavaScript iterate over object keys?

In JavaScript, when we use the for...in loop or the Object.keys() method, how does the internal engine iterate over the object keys?

I know this might slightly change from one implementation to another, but I'm sure there's a general approach, could you give a bird's-eye overview?

Thanks!

It's less about how object.keys works and more about how an object's properties are represented. In V8 there is in-object properties (same representation as C struct fields or Java object fields), fixed out-of-object properties stored in a fixed array and dynamic out-of-object properties stored in a hash table.

The layout of the in-object properties and the fixed out-of-object properties is stored separately in the object's hidden class. If the object's layout changes it gets a new hidden class. Like a Java's Class object , the hidden class object contains the names of the fixed properties and you simply iterate over that array.

When using hash table (aka dictionary, hashmap or normalized object) representation you must dynamically iterate over the hash table keys just like you iterate over any hash table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM