js给对象添加Iterator接口使之可被for of循环枚举

拥有Iterator接口的数据结构可以被for of遍历,

默认拥有Iterator接口的有:Map,Set,Array,String,类数组,arguments,NodeList

用for of遍历json对象,

let noIteratorObj = { name: 'LAPFUTURE', age: 21 };
for (let i of noIteratorObj) {
	console.log(i);
}

说noIteratorObj是不可被枚举的,也就是说这个对象没有遍历的接口,无法被for of遍历

试试普通数组:

let arr = [1,2,3];
let iters = arr[Symbol.iterator]();
console.log(iters.next()); // {value: 1, done: false }
console.log(iters.next()); // {value: 2, done: false }
console.log(iters.next()); // {value: 3, done: false }

给对象加Iterator接口:

let obj = {
				name: 'LAPFUTURE',
				age: 21,
				sex: 'boy',
				height: 180,
				likes: 'music',
				nowIndex: 0,
				[Symbol.iterator]: function() {
					return this;
				},
				next: function() {
					let keys = Object.getOwnPropertyNames(this);
					keys.splice(keys.indexOf('nowIndex'), 1);
					keys.splice(keys.indexOf('next'), 1);
					if (this.nowIndex < keys.length) {
						this.nowIndex = this.nowIndex + 1;
						return {
							value: this[keys[this.nowIndex - 1]],
							done: false,
						};
					} else {
						return {
							value: this[keys[this.nowIndex]],
							done: true,
						};
					}
				},
			};
for (let i of obj) {
	console.log(i);
}

js给对象添加Iterator接口使之可被for of循环枚举_第1张图片

这样算是给普通对象加上了遍历接口,可以被for of遍历

你可能感兴趣的:(js给对象添加Iterator接口使之可被for of循环枚举)