📜  for of js - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:18.223000             🧑  作者: Mango

For...of in JavaScript

The for...of statement is a new addition in modern JavaScript, which allows us to iterate over iterable objects.

Iterable Objects

Iterable objects are objects that implement the Symbol.iterator method, which returns an iterator object. Examples of built-in iterable objects in JavaScript include arrays, strings, maps, sets, and arguments objects.

Syntax of for...of
for (variable of iterable) {
  // code block to be executed
}
  • variable: This is the variable that will be assigned the value of each element in the iterable object during each iteration.
  • iterable: This is the iterable object that we want to loop through.
Example Usage
const arr = ['a', 'b', 'c'];

for (const element of arr) {
  console.log(element);
}
// Output:
// a
// b
// c

In this example, we create an array arr and loop through it using for...of. During each iteration, the element variable is assigned the value of the current element in the array.

We can also use for...of with strings:

const str = 'hello';

for (const char of str) {
  console.log(char);
}
// Output:
// h
// e
// l
// l
// o

In this example, we loop through the string str and output each character.

Conclusion

The for...of statement is a powerful tool for iterating over iterable objects in JavaScript. It provides a clean and concise syntax for looping through arrays, strings, maps, sets, and other iterable objects.