es6基礎0x015:for...of

0x000 概述

for...of是一個迭代可迭代對象的方式,可迭代對象包括ArrayMapSetStringTypedArrayarguments 對象等等

0x001 語法

for(variable of iterable){
    // statement
}

0x001 迭代數組

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

0x002 迭代字符串

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

0x003 迭代Set

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

0x004 迭代Map

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

0X005 迭代arguments

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

0x006 迭代Dom集合

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

0x007 總結

for...of只能迭代可迭代對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章