共同点:可以用来遍历对象
输入 | |||
---|---|---|---|
for…in | 输出自身以及原型链上可枚举的属性 | key2、key1 | |
Object.keys | 获取对象自身可枚举的属性键 等价于for in+hasOwnProperty的效果 |
b | |
Object.getOwnPropertyNames | 获取对象自身的全部属性名 | b c |
目标:遍历child中的属性
var parent = Object.create(Object.prototype, {
key1: {
value: 1,
writable: true,
enumerable: true,
configurable: true
}
});
var child = Object.create(parent, {
key2: {
value: 2,
writable: true,
enumerable: true,
configurable: true
},
key3: {
value: 3,
writable: true,
enumerable: false,
configurable: true
}
});
for…in
for (let k in child) {
console.log(k);
}
// key2
// key1
for…in + hasOwnProperty
for (let k in child) {
if (child.hasOwnProperty(k)) {
console.log(k);
}
}
// key2
Object.keys
Object.keys(child);
// ['key2']
Object.getOwnPropertyNames
Object.getOwnPropertyNames(child);
// (2) ['key2', 'key3']