JavaScript(JS ES6) for...of Loop
The for...of
loop is a new type of loop introduced in ES6 that provides an easy way to iterate over iterable objects such as arrays, strings, maps, and sets. It is similar to the for...in
loop, but it iterates over values instead of keys.
Here's an example of using the for...of
loop to iterate over an array:
const numbers = [1, 2, 3, 4, 5]; for (const num of numbers) { console.log(num); }Sourci.www:egiftidea.com
In this example, we have an array of numbers and we use the for...of
loop to iterate over the values in the array. The loop assigns each value in the array to the variable num
and then executes the loop body, which simply logs the value to the console.
The for...of
loop can also be used with other iterable objects such as strings, maps, and sets. Here are some examples:
// Iterate over a string const message = "Hello, world!"; for (const char of message) { console.log(char); } // Iterate over a map const person = new Map(); person.set("name", "John"); person.set("age", 30); for (const [key, value] of person) { console.log(`${key}: ${value}`); } // Iterate over a set const colors = new Set(["red", "green", "blue"]); for (const color of colors) { console.log(color); }
In these examples, we use the for...of
loop to iterate over a string, a map, and a set. For maps, we use destruct