📜  javascipr for of - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:04.010000             🧑  作者: Mango

JavaScript For...Of

JavaScript For...Of is a loop statement that is used to iterate over iterable objects like arrays, strings, maps, sets, etc. It was introduced in ES6 or ECMAScript 2015, and it simplifies the process of iterating over the elements of an iterable object by providing a clean syntax and eliminating the need to keep track of an index.

Syntax

The syntax of the for...of loop is as follows:

for (variable of iterable) {
   // code block to be executed
}
  • variable: The variable represents the current value of the iterable object in each iteration of the loop.

  • iterable: The iterable is an object or a collection of objects that can be iterated over, such as an array, a string, a map, a set, etc.

Examples
Iterating over an Array
const fruits = ['apple', 'banana', 'orange'];

for (const fruit of fruits) {
  console.log(fruit);
}
// Output: 'apple', 'banana', 'orange'
Iterating over a String
const word = 'hello';

for (const letter of word) {
  console.log(letter);
}
// Output: 'h', 'e', 'l', 'l', 'o'
Iterating over a Map
const students = new Map([
  ['John', 90],
  ['Jane', 95],
  ['Mark', 85]
]);

for (const [name, score] of students) {
  console.log(`${name} scored ${score}`);
}
// Output: 'John scored 90', 'Jane scored 95', 'Mark scored 85'
Iterating over a Set
const colors = new Set(['red', 'green', 'blue']);

for (const color of colors) {
  console.log(color);
}
// Output: 'red', 'green', 'blue'
Advantages
  1. Simplifies the process of iterating over iterable objects by providing a clean syntax.

  2. Eliminates the need to keep track of an index.

  3. It is faster and more efficient than the traditional For loop.

  4. Can be used with a variety of iterable objects.

Conclusion

JavaScript for...of loop is a powerful tool for iterating over iterable objects like arrays, strings, maps, and sets. It simplifies the syntax and eliminates the need for keeping track of an index, making it faster and more efficient than traditional For loop.