JS 對象遍歷知多少?
最前面
本文主要是對 JS 對象(不含數(shù)組、Map、Set 結(jié)構(gòu))的 7個遍歷方法進行總結(jié)歸納,寫該文章的這天恰好是我最喜愛的球星艾弗森的 45 周歲生日,因此本文會以艾弗森的基本資料為模板生成一個 JS 對象并對其進行遍歷 。
定義對象
首先讓我們定義如以下代碼所示的對象 player:
- const player = {
 - name: 'Allen Iverson',
 - [Symbol('birthday')]: '1975/06/07',
 - };
 - Object.defineProperties(player, {
 - isHallofFame: {
 - enumerable: false,
 - value: true,
 - },
 - [Symbol('ScoreKingTime')]: {
 - enumerable:false,
 - value: 4,
 - },
 - });
 - Object.defineProperties(player.__proto__, {
 - university: {
 - enumerable: true,
 - value: 'Georgetown',
 - },
 - team: {
 - enumerable: false,
 - value: '76ers',
 - },
 - [Symbol('country')]: {
 - enumerable: true,
 - value: 'USA',
 - },
 - [Symbol('hometown')]: {
 - enumerable: false,
 - value: 'Virginia',
 - },
 - });
 
如上述代碼所示,定義了一個 player 的對象,其共有以下 8 個屬性:
通過控制臺的輸出觀察也更直觀:
其中淺顏色的屬性都是不可枚舉的屬性,__proto__下的屬性則為其原型上(即 Object.prototype)的屬性,Symbol 類型的值自然為 Symbol 屬性
for...in
MDN:The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.
- for(const name in player) {
 - console.log('name:', name);
 - }
 - // name: name
 - // name: university
 
for...in 循環(huán)是我們較為常用的遍歷對象方法了,結(jié)合 MDN 里所言以及輸出結(jié)果不難得出其遍歷的屬性,包含自身以及原型上所有可枚舉的屬性,不包含 Symbol 屬性。因為其可遍歷到原型上可枚舉的屬性,因此我們的代碼中通常會多出一句這樣的判斷(如果我們不需要原型上的屬性):
- for(const name in player) {
 - if (Object.prototype.hasOwnProperty.call(player, name)) {
 - console.log('name:', name);
 - }
 - }
 - // name: name
 
Object.keys
MDN:The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.
- const keys = Object.keys(player);
 - console.log('keys:', keys);
 - // keys: ["name"]
 
Object.keys 大概是我們最常用的遍歷方法了,如在 Vue 源碼對 data 進行遍歷響應(yīng)式處理也是用這個方法。通過輸出結(jié)果也表明:其返回的是所有自身可枚舉的屬性(不含 Symbol 屬性),不包含原型上的任何屬性。
Object.getOwnPropertyNames
MDN:The Object.getOwnPropertyNames() method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly in a given object.
- const ownPropertyNames = Object.getOwnPropertyNames(player);
 - console.log('ownPropertyNames:', ownPropertyNames);
 - // ownPropertyNames: ["name", "isHallofFame"]
 
Object.getOwnPropertyNames 返回的是所有自身的屬性(包含不可枚舉屬性但不包含 Symbol 屬性),不包含原型上的任何屬性。
Object.getOwnPropertySymbols
MDN:The Object.getOwnPropertySymbols() method returns an array of all symbol properties found directly upon a given object.
- onst ownPropertySymbols = Object.getOwnPropertySymbols(player);
 - console.log('ownPropertySymbols:', ownPropertySymbols);
 - // ownPropertySymbols: [Symbol(birthday), Symbol(ScoreKingTime)]
 
通過輸出不難得出 Object.getOwnPropertySymbols 返回的是自身的所有 Symbol 屬性(包含不可枚舉的),但是不含原型上的任何屬性。
Reflect.ownKeys
MDN:The static Reflect.ownKeys() method returns an array of the target object's own property keys.
- const ownKeys = Reflect.ownKeys(player);
 - console.log('ownKeys:', ownKeys)
 - // ownKeys: ["name", "isHallofFame", Symbol(birthday), Symbol(ScoreKingTime)]
 
Reflect.ownKeys 返回的是自身的所有屬性(包含不可枚舉的以及所有 Symbol 屬性),不包含原型 上的任何屬性。
Object.values
MDN:The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)
- const values = Object.values(player);
 - console.log('values:', values);
 - // values: ["Allen Iverson"]
 
Object.values 同 Object.keys 一樣,其遍歷的是所有自身可枚舉的屬性(不含 Symbol 屬性),不包含原型上的任何屬性。但與 Object.keys 不同的是:其返回的不再是 key 值而是 value 值集合。
Object.entries
MDN: The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well).
- const entries =Object.entries(player);
 - console.log('entries:', entries);
 - // entries: [["name", "Allen Iverson"]]
 
其也同 Object.keys 一樣,遍歷的是所有自身可枚舉的屬性(不含 Symbol 屬性),不包含原型上的任何屬性。不同的是,其返回值是 [key, value]的集合。Object.entries 在我們平時的開發(fā)中可能很少用到,但是其可配合Object.fromEntries一起使用:有以下代碼:
- // 對象轉(zhuǎn)換
 - const object1 = { a: 1, b: 2, c: 3 };
 - const object2 = Object.fromEntries(
 - Object.entries(object1)
 - .map(([ key, val ]) => [ key, val * 2 ])
 - );
 - console.log(object2);
 - // { a: 2, b: 4, c: 6 }
 
總結(jié)
結(jié)合文章中的代碼輸出結(jié)果可得到以下表格:
簡而言之:
- 只有 for...in 可以遍歷到原型上的屬性
 - Object.getOwnPropertyNames 和 Reflect.ownKeys 可獲取到不可枚舉的屬性
 - Object.getOwnPropertySymbols 和 Reflect.ownKeys 可獲取到 Symbol 屬性
 


















 
 
 




 
 
 
 