Home >Web Front-end >JS Tutorial >Simple usage example of for...of in ES6

Simple usage example of for...of in ES6

不言
不言Original
2018-11-14 16:32:281947browse

This article brings you a simple usage example of for...of in ES6. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Overview

for...of is a way to iterate iterable objects. Iterable objects include Array, Map, Set, String, TypedArray, arguments objects, etc.

Syntax

for(variable of iterable){
    // statement
}

Iteration Array

for(let a of [1,2,3]){
    console.log(a)
} 
// 1
// 2
// 3

Iteration String

for(let s of 'hello'){
    console.log(s)
}
// h
// e
// l
// l
// o

Iteration Set

for(let s of new Set([1,2,3])){
    console.log(s)
}
// 1
// 2
// 3

0x004 IterationMap

for(let s of new Map([[1,1],[2,2]])){
    console.log(s)
}
// (2) [1, 1]
// (2) [2, 2]

Iterate arguments

(function() {
  for (let argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3);

Iterate Dom collection

for(let p of document.getElementsByTagName('p')){
    console.log(p)
}
// <p>...<p>
// <p>...<p>
// <p>...<p>
// <p>...<p>
...

Summary

for...of can only iterate iterable objects


The above is the detailed content of Simple usage example 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