1、for。。。in遍历
2、Object.keys 遍历
3、Object.values 遍历
4、Object.entries 遍历
5、getOwnPropertyNames 遍历
6、forEach遍历
下面的代码案例我们都将以Person的实例作为遍历对象。
const Person = function(){
this.name = 'Person'
this.age = 25
this.isMan = false
Person.prototype.address = '北京'
Person.prototype.sayName=function(){
console.log(this.name);
}
}
const person1 = new Person()
一、for。。。in遍历,会遍历对象内的和原型内属性为Enumerable的属性,代码如下:
for(const item in person1){
console.log(item,person1[item]);
}
结果如下:
name: Person
age: 25
isMan: false
address: 北京
sayName: function(){ console.log(this.name); }
二、Object.keys() , 会返回对象的属性名组成的数组,但不会去原型中查找属性。
console.log(Object.keys(person1))
结果如下:
['name','age','isMan']
三、Object.values(),跟Object.keys一样不过 它返回的是属性值的数组。
console.log(Object.values(person1))
结果如下:
['Person', 25, false]
四、Object.entries(), 他返回的是以键值对形式的数组的数组。
console.log(Object.entries(person1));
结果如下:
[
[
"name",
"Person"
],
[
"age",
25
],
[
"isMan",
false
]
]
五、Object.getOwnPropertyNames() ,更Object.keys是一样的
console.log(Object.getOwnPropertyNames(person1))
结果如下:
[
"name",
"age",
"isMan"
]
六、我看到很多博客都用forEach封装一个方法挂载到object的构造函数中,在需要时调用。封装代码如下:
// 将自定义的方法挂载到Object的构造函数中,函数接收一个对象一个回调方法
Object.prototype.constructor.forEach = function(obj,callback){
// 判断回调是否是一个函数
if(typeof(callback) === 'function'){
let i = 0;
for(let key in obj){
callback(obj[key],i,key);
i ++;
}
return;
}
// 传入的回调如果不是function,那么就抛出错误
throw new Error (callback + ' is not a function!,You can use it like this: Object.forEach(obj,(item,index,key)=>{...}) ')
}
var obj = {
avatar:'https://a.jpg',
nickName:'昵称',
UID:'5616259',
}
Object.forEach(obj,(item,index,key)=>{
console.log(item, index, key);
})
=> https://a.jpg 0 avatar
=> 昵称 1 nickName
=> 5616259 2 UID
但我个人是不喜欢这种方式的原因是封装是用for。。in封装的它会遍历原型中enumberable为true的属性,会带来不确定性。我更喜欢用forEach或者for of 搭配Objec.keys等方法来完成遍历,代码如下:
Object.getOwnPropertyNames(person1).forEach(item=>{
console.log(item,person1[item])
})
返回结果:
name: Person
age: 25
isMan: false
当然也可以用for。。of,代码如下:
for(const item in Object.getOwnPropertyNames(person1)){
console.log(item,person1[item])
}
结果如下:
name: Person
age: 25
isMan: false