使用ES5实现iterator遍历器接口(遍历器生成函数)

1.es5实现

	const obj = {
	  name: 'ha',
	  age: 12,
	  sex: 'man'
	};
	
	obj[Symbol.iterator] = function(){
	  let index = 0;
	  const keysArr  = Object.keys(this);
	  const _this = this;
	  return {
	    next: function () {
	      if (index < keysArr.length) {
	
	        return {
	          value: keysArr[index] + '--' + _this[keysArr[index++]],
	          done: false
	        }
	      } else {
	        return {
	          value: undefined,
	          done:true
	        }
	      }
	    }
	  }
	};
	
	
	
	console.log([...obj]);

  • 这里闭包的作用就是记录游标的位置。

结果如下:
在这里插入图片描述

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