for-of Loop

PHPz
PHPzOriginal
2024-08-24 11:21:021117browse

for-of Loop

  • Mainly used to loop over arrays.
  • Indirectly can be used to loop over objects. Depends on what we want to loop over i.e property-names(also known as keys), property-values or both.
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, '

The above is the detailed content of for-of Loop. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn