ES6-iterable iterator

【 for...of 】

const m = new Map()
m.set('foo','123');
m.set('bar','345');
for(const [key,value] of m) { // 使用es6解构
    console.log(key,'=',value) // foo=123;bar=345
}
const obj = {foo:123,bar:456};  // for of 不能遍历普通对象,必须是有迭代器的数据类型
for(const item of obj ) {
    console.log(item)  // 报错:Uncaught TypeError: obj[Symbol.iterator] is not a function
}

Which data structures have Symbol.iteratoer properties?

  • Array
  • Map
  • Set
  • String
  • arguments object
  • Nodelist object, which is the collection of dom list obtained

 

[Iterable interface]

Implementing the iterable interface is the premise of for...of

image.png

The iterable interface is to maintain a data pointer, value is the value, and done indicates whether the traversal is completed

// iterable使用
const set = new Set(['foo','bar','lazy']);
const iterator = set[Symbol.iterator]();
console.log(iterator.next())  // value: 'foo',done:false
console.log(iterator.next())  // value: 'bar',done:false
console.log(iterator.next())  // value: 'lazy',done:false
console.log(iterator.next())  // value: 'undefined',done:true

// 如果想用for...of 遍历对象
// 使用 Object.keys() 获取对象的 key值集合后,再使用 for of
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.keys(obj)) {
    console.log(o) // a,b,c,d
}
//或者使用内置的Object.values()方法获取对象的value值集合再使用for of
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.values(obj)) {
    console.log(o) // 1,2,3,4
}

 

[Iterable implementation]

Guess you like

Origin blog.csdn.net/qq_42269433/article/details/115273507