for of and iterator

1. The working principle of for of

The for...of loop will first look for the Symbol.iterator property of the accessed object. This property points to the iterator object. After finding the iterator object, it traverses all return values ​​by calling the next() method of the iterator object.

2. Objects that can be traversed with for of

Array, string, arguments, set container, map container. 因为它们都有内置的Symbol.iterator接口.

3. Simulate the implementation of the Symbol.iterator interface to traverse objects

let targetDate = {
    
    
	[Symbol.iterator]: function () {
    
    
		let nextIndex = 0;	//记录指针位置
		return {
    
    
			next: function () {
    
    
				return nextIndex < this.length? {
    
    value: this[nextIndex++], done: false} : {
    
    value: undefined, done: true};
			}
		}
	}
}
// 这样targetDate就可以使用let of遍历了

4. Use the Generator function to simulate the implementation of the Symbol.iterator interface

let obj = {
    
     username: 'kobe', age: 39 };
obj[Symbol.iterator] = function* myIterator() {
    
    
    for (let key of Object.keys(this)) {
    
    
        yield key
    }
}
for(let i of obj) {
    
    
    console.log(i);	// username age
}

Guess you like

Origin blog.csdn.net/weixin_43757001/article/details/115360652