for-of

for-of可以遍历数组,类似数组的对象以及通常所有可迭代的对象(map,set,DOM集合)

# 遍历数组

  • 无需其他变量来保持索引
  • arr.entries() 方法返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)
  • 迭代对象? 是支持迭代协议的对象(字符串、数组、类数组、集合、映射、...), Symbol.iterator可检查数据类型是否可迭代
const arr = [1, 2, 3]
// 检查数据类型是否可迭代
const iterator = arr[Symbol.iterator]()
iterator.next() // { value: 1, done: false }
//
for (const item of arr) { console.log(item) }
// 1 2 3

for (const [index, item] of arr.entries()) {
    console.log(index, item)
}
/*
    0 1
    1 2
    2 3
*/
//
const list = [{ name: 'Ethan', sex: 'male' }, { name: 'Linna', sex: 'female' }]

for (const { name } of list) {
    console.log(name)
}
// Ethan Linna

# 遍历类数组

function sum() {
    for (const arg of arguments) {
        console.log(arg)
    }
}

sum(1, 2, 3) // 1 2 3

function sum() {
    let sum = 0
    for (const arg of arguments) {
        sum += arg
    }
    return sum
}
sum(1, 2, 3) // 6

# 遍历字符串

const str = 'Hello'
for (const s of str) {
    console.log(s)
}
// 'H' 'e' 'l' 'l' 'o'

# 遍历对象

const obj = { name: 'Ethan', sex: 'Male' }
for (const [key, val] of Object.entries(obj)) {
    console.log(key, val)
}
/* 
name Ethan
sex Male
*/

# 遍历DOM集合

//每个 DOM 元素的children属性都是HTMLCollection
const children = document.body.children
for (const child of children) {
    cosnole.log(child)
}

/*
    each child of <body>
    <div>...</div>
    <script>...</script>
*/
// nodelist
const imgs = document.querySelectorAll('img')
for (const img of imgs) {
    console.log(img)
}
/*
    each img in this document
    <img />...
*/

# 遍历MAP/Set

const map = new Map()
map.set(1, 'one')
map.set(2, 'two')

for (const [key, val] of map) {
    console.log(key, val)
}
/* 
    1 'one'
    2 'two'
*/

const sets = new Set([1, 2, 3, 4, 5])
for (const set of sets) {
    console.log(set)
}
// 1 2 3 4 5

# 性能

  • for-of应该比for慢
  • 调用迭代器比增加索引访问开销大

# 拓展知识点