JS中for…of和for…in的区别
for…in主要是为了遍历对象而产生,不适用于遍历数组,for…of循环可以用来遍历数组,类数组对象、字符串、、、
1)遍历对象
for…of遍历获取对象的键值,for…in获取对象的键名
for…in会遍历对象的整个原型链,for…of只遍历当前对象
2)数组的遍历
for…in返回数组中所有可枚举的属性,for…of返回数组的下表对应的属性值
function Person(name,age,sex){
this.name=name
this.age=age
this.sex=sex
}
Person.prototype.height=188
var p=new Person('张三',18,'男')
p[Symbol.iterator]=function(){
var keys=Object.keys(this)
var index=0
return {
next(){
if(index<keys.length){
return {value:p[keys[index++]],done:false}
}
else{
return {value:undefined,done:true}
}
}
}
}
for(let value of p){
console.log(value);// 张三 18 男
}
for (let value in p) {
console.log(value);//name age sex height
}