📅  最后修改于: 2023-12-03 15:00:50.544000             🧑  作者: Mango
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.
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.
Here are a few examples of how to use the for...of
loop in JavaScript:
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
Output:
red
green
blue
const name = 'John';
for (const letter of name) {
console.log(letter);
}
Output:
J
o
h
n
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
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.