Home > Web Front-end > JS Tutorial > body text

for-of Loop

PHPz
Release: 2024-08-24 11:21:02
Original
1043 people have browsed it

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, '
Copy after login

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

source:dev.to
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!