JavaScript 中 for in 和for of的区别

重点内容

  • for in 取 key; for of 取 value
  • for of 只能用于数组遍历,for in还可以用于对象属性的遍历

eg,

1. 遍历数组:
let array = [1,2,3,'lynn','Lanny']
console.log('for of: ')
for (let value of array){
  console.log(value);
}
console.log('\n'+'for in: ')
for (let key in array){
  console.log(key);
}

控制台打印

for of:
1
2
3
lynn
Lanny

for in:
0
1
2
3
4
1. 遍历对象:
function Person(){
  this.name = 'Lanny';
  this.age = '24';
  this.sleep = ()=>{
    console.log('I am sleeping~~~~');
  }
}

Person.prototype.sayHello = (name)=>{
  console.log('hello ' + name);
}

let person = new Person();
person.sayHello('Lynn');

for(let key in person){
  if(person.hasOwnProperty(key)){      //不遍历原型方法
    console.log(key);
  }
}

控制台打印:

hello Lynn
name
age
sleep

你可能感兴趣的:(杂类)