javascript 遍历对象的几种方法

分享几种 javascript 遍历对象的方法

1. for(let key in obj) 形式

<script>
const obj = {
    id:1,
    name:'zhangsan',
    age:18
}
for(let key in obj){
    console.log(key + '---' + obj[key])
}
</script>

2. Object.keys() 形式

<script>
const obj = {
    id:1,
    name:'zhangsan',
    age:18
}
Object.keys(obj).forEach((key)=>{
     console.log(key+' : '+obj[key]);
});
</script>

3. Object.getOwnPropertyNames() 形式

<script>
const obj = {
    id:1,
    name:'zhangsan',
    age:18
}
Object.getOwnPropertyNames(obj).forEach(function(key){
    console.log(key+ '---'+obj[key])
})
</script>