- for-in
对象属性的 Enumerable 表示属性是否可以通过 for-in 循环返回,默认为true
对象自身上的及其原型链上的可枚举属性都可以遍历到
function Person() {}
Person.prototype.name = 'person'
Person.prototype.age = 20
Person.prototype.sayName = function(){
console.log(this.name);
}
Object.prototype.say = function() {
console.log('Object.prototype');
}
const p1 = new Person()
p1.work = 'worker'
p1.name = 'hhh'
console.log(p1);
for (let i in p1) {
console.log(i); //work name age sayName say
}
for (let i in Person.prototype) {
console.log(i); //age name sayName say
}
- Object.keys()
该方法接受一个对象,返回该对象所有可枚举属性的字符串数组
console.log(Object.keys(p1)); // ['work', 'name']
console.log(Object.keys(Person.prototype)); // ['age', 'name', 'sayName']
console.log(Object.keys(Object.prototype)); // ['say']
- Object.getOwnPropertyNames()
可列出所有实例属性,无论是否可以枚举
console.log( Object.getOwnPropertyNames(p1)); // ['work', 'name']
console.log( Object.getOwnPropertyNames(Person.prototype)); // ['constructor', 'age', 'name', 'sayName']
本文探讨了JavaScript中对象属性的遍历方法,包括for-in循环、Object.keys()及Object.getOwnPropertyNames()等,并展示了如何通过这些方法获取对象自身及其原型链上的属性。
545

被折叠的 条评论
为什么被折叠?



