JavaScriptのfor inとfor ofの違い

2902 ワード

重点の内容
  • 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('
    '
    +'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