首页 >web前端 >js教程 >for-of 循​​环

for-of 循​​环

PHPz
PHPz原创
2024-08-24 11:21:021116浏览

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