
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!