📅  最后修改于: 2023-12-03 14:41:18.182000             🧑  作者: Mango
In JavaScript, the for of
loop is used to iterate over iterable objects such as arrays, strings, and maps. Unlike the traditional for
loop, it does not loop through the values or keys of an object, but rather it loops through the iterable objects. This loop simplifies the code and makes it easier to read and write.
for (variable of iterable) {
// Code block to be executed
}
Variable: A variable that represents each item of an iterable object during the iteration.
Iterable: An object that has the Symbol.iterator
method, which is called when the loop is initiated to return an iterator object.
const fruits = ['apple', 'orange', 'banana'];
for (const fruit of fruits) {
console.log(fruit);
}
// Output:
// apple
// orange
// banana
In the above example, the for of
loop is used to iterate over an array of fruits. The variable fruit
represents each item of the array during each iteration of the loop, and its value is printed on the console.
The for of
loop in JavaScript provides a simple and efficient way to iterate over iterable objects. It simplifies the code and makes it easier to read and write. However, it has some limitations and is not supported by older browsers. Therefore, it is recommended to use it in modern web development projects.