张宇航,微医前端技术部医保支撑组,一个不文艺的处女座程序员。
本文主要是对 JS 对象(不含数组、Map、Set 结构)的 7个遍历方法进行总结归纳,写该文章的这天恰好是我最喜爱的球星艾弗森的 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 个属性:
原型属性 | 可枚举 | Symbol 属性 | 值 | |
---|---|---|---|---|
name | 否 | 是 | 否 | Allen Iverson |
birthday | 否 | 是 | 是 | 1975/06/07 |
isHallofFame | 否 | 否 | 否 | true |
ScoreKingTime | 否 | 否 | 是 | 4 |
university | 是 | 是 | 否 | Georgetown |
team | 是 | 否 | 否 | 76ers |
country | 是 | 是 | 是 | USA |
hometown | 是 | 否 | 是 | Virginia |
通过控制台的输出观察也更直观:
其中浅颜色的属性都是不可枚举的属性,__proto__下的属性则为其原型上(即 Object.prototype)的属性,Symbol 类型的值自然为 Symbol 属性
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 循环是我们较为常用的遍历对象方法了,结合 MDN 里所言以及输出结果不难得出其遍历的属性,包含自身以及原型上所有可枚举的属性,不包含 Symbol 属性。因为其可遍历到原型上可枚举的属性,因此我们的代码中通常会多出一句这样的判断(如果我们不需要原型上的属性):
for(const name in player) {
if (Object.prototype.hasOwnProperty.call(player, name)) {
console.log('name:', name);
}
}
// name: name
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 进行遍历响应式处理也是用这个方法。通过输出结果也表明:其返回的是所有自身可枚举的属性(不含 Symbol 属性),不包含原型上的任何属性。
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 属性),不包含原型上的任何属性。
MDN:The Object.getOwnPropertySymbols() method returns an array of all symbol properties found directly upon a given object.
const ownPropertySymbols = Object.getOwnPropertySymbols(player);
console.log('ownPropertySymbols:', ownPropertySymbols);
// ownPropertySymbols: [Symbol(birthday), Symbol(ScoreKingTime)]
通过输出不难得出 Object.getOwnPropertySymbols 返回的是自身的所有 Symbol 属性(包含不可枚举的),但是不含原型上的任何属性。
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 属性),不包含原型 上的任何属性。
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 值集合。
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 在我们平时的开发中可能很少用到,但是其可配合Object.fromEntries一起使用:有以下代码:
// 对象转换
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 }
结合文章中的代码输出结果可得到以下表格:
含原型属性 | 含不可枚举 | 含 Symbol 属性 | 返回值 | |
---|---|---|---|---|
for...in | 是 | 否 | 否 | key |
Object.keys | 否 | 否 | 否 | [key...] |
Object.getOwnPropertyNames | 否 | 是 | 否 | [key...] |
Object.getOwnPropertySymbols | 否 | 是(只有 symbol) | 是 | [key...] |
Reflect.ownKeys | 否 | 是 | 是 | [key...] |
Object.values | 否 | 否 | 否 | [value...] |
Object.entries | 否 | 否 | 否 | [[key,value]...] |
简而言之: