转自:https://blog.csdn.net/weixin_43387238/article/details/85038414
例如有这么一个对象:
let obj = {
name: 'Kamen',
age: '23',
hobby: 'eat eat eat'
}
方法一:转化为操作数组forEach遍历
//遍历对象属性
Object.keys(obj).forEach(key => {
console.log(key)
})
方法二:for/in遍历
for( let key in obj ){
//遍历对象属性
console.log(key)
//遍历对象属性值
console.log(obj[key])
}
注意:该方法会继承原型链的所有属性,例如:
Object.prototype.pet = 'open'
for( let key in obj ){
console.log(key)
console.log(obj[key])
}
console.log(obj)
上述情况可以使用hasOwnProperty避免:
Object.prototype.pet = 'open'
for( let key in obj ){
if (obj.hasOwnProperty(key) === true){
console.log(key)
console.log(obj[key])
}
}
console.log(obj)