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

Iteration Stament i.e for-of loop

WBOY
Release: 2024-08-24 11:06:35
Original
1071 people have browsed it

Iteration Stament i.e for-of loop

for-of:

  • Introduced in ES6
  • Usually a loop has counter, check-condition, updating counter. A for-of loop doesn't have anything like that.
  • continue-break both can be used with it.
  • Meant to give us current element.
fruits = ['banana','apple','peach','orange','mango','guava','water-melon'];

for(const item of fruits){
  console.log(item);
}

'banana'
'apple'
'peach'
'orange'
'mango'
'guava'
'water-melon'
Copy after login
- If an array if looped over in the form of array.entries(), then the result will be each element in form of an array with index : value.

for(const item of fruits.entries()){
  console.log(item);
}

[ 0, 'banana' ] 
[ 1, 'apple' ] 
[ 2, 'peach' ] 
[ 3, 'orange' ] 
[ 4, 'mango' ] 
[ 5, 'guava' ] 
[ 6, 'water-melon' ]

// Transform it into a single array comprising of sub-arrays:
fruits.entries(); // Object [Array Iterator] {}

[...fruits.entries()]; 
// [ [ 0, 'banana' ], [ 1, 'apple' ], [ 2, 'peach' ], [ 3, 'orange' ], [ 4, 'mango' ], [ 5, 'guava' ], [ 6, 'water-melon' ] ]

// Transform into a single array using for-of loop:
-> Method 1
for(const item of fruits.entries()){
  console.log(`${item[0] + 1} : ${item[1]}`);
}
// '1 : banana' '2 : apple' '3 : peach' '4 : orange' '5 : mango' '6 : guava' '7 : water-melon'

-> Method 2
for(const [i,el] of fruits.entries()){
  console.log(`${i + 1} : ${el}`);
}
// '1 : banana' '2 : apple' '3 : peach' '4 : orange' '5 : mango' '6 : guava' '7 : water-melon'

Copy after login

The above is the detailed content of Iteration Stament i.e 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!