JS 对象遍历

275 阅读1分钟
方法 是否继承 是否包含不可枚举类型 是否包含 Symbol
Object.keys() Object.values() Object.entries()
Object.getOwnPropertyNames()
Reflect.ownKeys()
for...in

for...of 不能遍历普通对象,有两个方法可以实现,见下文

示例

class Student{
    constructor(name,school){
        this.name = name;
        this.school = school;
    }
}

// prototype
Student.prototype.age = 18;

let s = new Student('wen','... university');

// symbol
s[Symbol("id")] = '123';

// enumerable = false
Object.defineProperty(s,'sex',{
    value:'female',
    enumerable:false
});

console.log("Object.keys()");
console.log(Object.keys(s));

console.log("\n\nObject.getOwnPropertyNames()");
console.log(Object.getOwnPropertyNames(s));

console.log("\n\nReflect.ownKeys()");
console.log(Reflect.ownKeys(s));

console.log("\n\nfor...in");
for(var i in s) {
    console.log(i,":",s[i]);
}

输出结果:

Object.keys()
[ 'name', 'school' ]


Object.getOwnPropertyNames()
[ 'name', 'school', 'sex' ]


Reflect.ownKeys()
[ 'name', 'school', 'sex', Symbol(id) ]


for...in
name : wen
school : ... university
age : 18

for...of

for...of 不能遍历普通对象,有两个方法可以实现

  1. 使用 Object.keys 方法将对象的键名生成一个数组,然后遍历这个数组
for (var key of Object.keys(someObject)) {
  console.log(key + ': ' + someObject[key]);
}
  1. 使用 Generator 函数将对象重新包装
function* entries(obj) {
  for (let key of Object.keys(obj)) {
    yield [key, obj[key]];
  }
}
for (let [key, value] of entries(obj)) {
  console.log(key, '->', value);
}