Home >Web Front-end >Front-end Q&A >What is the usage of for of in es6

What is the usage of for of in es6

WBOY
WBOYOriginal
2022-03-31 10:37:202317browse

In es6, "for of" is used to traverse the data structure deployed with the "Symbol.iterator" attribute. The "for of" loop is a method of traversing all data structures. The syntax is "for(var value of Data structure object){console.log(value);}".

What is the usage of for of in es6

The operating environment of this tutorial: Windows 10 system, ECMAScript version 6.0, Dell G3 computer.

What is the usage of for of in es6

ES6 introduces the for...of loop as a unified method to traverse all data structures.

As long as a data structure is deployed with the Symbol.iterator attribute, it is regarded as having an iterator interface, and its members can be traversed using a for...of loop, that is, for... What is called inside the of loop is the Symbol.iterator method of the data structure.

The range that the for...of loop can use:

  • String;

  • Array;

  • Set and Map structures;

  • Some array-like objects (such as arguments objects, DOM NodeList objects);

  • Generator object.

Usage example

var arr = ['nick','freddy','mike','james'];
for(var item of arr){
    console.log(item);
}

Output result:

What is the usage of for of in es6

Traverse each item in the array.

Usage example

var arr = [
    { name:'nick', age:18 },
    { name:'freddy', age:24 },
    { name:'mike', age:26 },
    { name:'james', age:34 }
];
for(var item of arr){
    console.log(item.name,item.age);
}

Output result:

What is the usage of for of in es6

Traverse each item in the array.

【Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of What is the usage of for of in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn