📅  最后修改于: 2023-12-03 15:16:04.010000             🧑  作者: Mango
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.
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.
const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
console.log(fruit);
}
// Output: 'apple', 'banana', 'orange'
const word = 'hello';
for (const letter of word) {
console.log(letter);
}
// Output: 'h', 'e', 'l', 'l', 'o'
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'
const colors = new Set(['red', 'green', 'blue']);
for (const color of colors) {
console.log(color);
}
// Output: 'red', 'green', 'blue'
Simplifies the process of iterating over iterable objects by providing a clean syntax.
Eliminates the need to keep track of an index.
It is faster and more efficient than the traditional For loop.
Can be used with a variety of iterable objects.
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.