📜  forof - Javascript (1)

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

For... Of in JavaScript

Introduction

In JavaScript, for...of is a new loop statement introduced in ES6. It provides an easy and concise way to iterate through iterable objects like arrays, strings, maps, and sets.

Syntax

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

for (variable of iterable) {
  // code block to be executed
}

Here, variable is a new variable that is created on each iteration and is assigned the current value of the iterable object. iterable is an object that implements the iterable protocol.

Examples

Here are a few examples of how to use the for...of loop in JavaScript:

Iterating Through An Array
const colors = ['red', 'green', 'blue'];

for (const color of colors) {
  console.log(color);
}

Output:

red
green
blue
Iterating Through A String
const name = 'John';

for (const letter of name) {
  console.log(letter);
}

Output:

J
o
h
n
Iterating Through A Map
const myMap = new Map();

myMap.set('firstName', 'John');
myMap.set('lastName', 'Doe');

for (const [key, value] of myMap) {
  console.log(`${key}: ${value}`);
}

Output:

firstName: John
lastName: Doe
Conclusion

The for...of loop provides a simple and easy-to-use way to iterate through iterable objects in JavaScript, making it simpler to write for loops with fewer lines of code.