對象遍歷的幾種方法


 

1.js對象 用for in遍歷 如:for(let item in st){ console.log(item) } // 返回的是鍵也是就是屬性名。

  如果要返回的是鍵值,則 for(let item in st ) { console.log(st[item]) } // 此時依次輸出鍵值

let persons = {
  120: { name: 'bob', age: 16, class: 2},
  130: { name: 'lucy', age: 18, class: 1},
  140: { name: 'mary', age: 14, class: 2},
  150: { name: 'jhon', age: 19, class: 1},
  160: { name: 'jack', age: 17, class: 2}
}
for(let item in this.persons) { if(this.persons[item].name === 'jack') {   console.log(`Hi, ${this.persons[item].name}, 最近好嗎`); // "Hi, jack, 最近好嗎" } }

 

 

2.數組對象用for of 遍歷時 for(let item of arr){} // 返回為值。

 

3.Set 對象用for of 遍歷時 for(let item of arr){} // 返回為可以說是鍵也可以說是值 因為他的鍵和值 是一樣的。

 Set實例對象的values() keys()方法遍歷返回的都是一樣的,原因是Set實例鍵名和鍵值是一樣的,,假設arr為Set對象的實例,如下:

 for(let item of arr.keys()) {} // 遍歷返回鍵名

 for(let item of arr.values()) {} // 遍歷返回鍵值

 for(let item of arr.entries()) {} // 返回鍵值對組成的數組,如:['key', 'value']

 

4.Map對象用for of 遍歷時 for(let item of arr){} // 返回為鍵值對的數組。

 

 

引自:https://www.cnblogs.com/woshinidaye/p/6753851.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM