简体   繁体   English

JavaScript在内部如何遍历对象键?

[英]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? 在JavaScript中,当我们使用for...in循环或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. 它与object.keys的工作原理无关,而与对象的属性表示方式有关。 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. 在V8中,存在对象内属性(与C结构字段或Java对象字段相同的表示形式),存储在固定数组中的固定对象外属性和存储在哈希表中的动态对象外属性。

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. 就像Java的Class对象一样 ,隐藏的类对象包含固定属性的名称,您只需遍历该数组即可。

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. 当使用哈希表(又名字典,哈希图或规范化对象)表示形式时,必须像对任何哈希表进行迭代一样,对哈希表键进行动态迭代。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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