首頁 >web前端 >js教程 >for-of 連環

for-of 連環

PHPz
PHPz原創
2024-08-24 11:21:021146瀏覽

for-of Loop

  • 主要用於循環數組。
  • 間接可用來循環物件。取決於我們想要循環的內容,即屬性名稱(也稱為鍵)、屬性值或兩者。
const seasons = {
  mar: 'summer',
  jul: 'monsoon',
  sep: 'autumn',
  nov: 'spring',
  jan: 'winter'
}

//Loop over property-keys & return in an array
const kys = Object.keys(seasons);
kys;             // [ 'mar', 'jul', 'sep', 'nov', 'jan' ]

//Loop over property-values & return in an array
const vals = Object.values(seasons);
vals;            // [ 'summer', 'monsoon', 'autumn', 'spring', 'winter' ]

//Loop over entries i.e index-with-its-corresponding-value & return in an array of arrays
const item = Object.entries(seasons);
item;           // [ [ 'mar', 'summer' ], [ 'jul', 'monsoon' ], [ 'sep', 'autumn' ], [ 'nov', 'spring' ], [ 'jan', 'winter' ] ]

for(const x of item){
  console.log(x);
}               // [ 'mar', 'summer' ] [ 'jul', 'monsoon' ] [ 'sep', 'autumn' ] [ 'nov', 'spring' ] [ 'jan', 'winter' ]

for(const [key, val] of item){
  console.log(`${key} ${val}`);
}               // 'mar summer' 'jul monsoon' 'sep autumn' 'nov spring' 'jan winter'

// Total no of properties on the object
console.log(`${Object.keys(seasons).length}`);    // '5'

let final = `Total ${Object.keys(seasons).length} seasons: `;

for(const season of Object.values(seasons)){
  // Loop over name of each property
  final += `${season}, `;
}               //  'Total 5 seasons: summer, monsoon, autumn, spring, winter, '

以上是for-of 連環的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn