ECMAScript6 给对象实现 iterator 方法

Object.prototype[Symbol.iterator] = function(){
	let index = 0,
		_this = this;
	return {
		next: function(){
			return index < _this.length ? 
				{ value: d[index++], done: false }:
				{ value: undefined, done:true };
		}
	}
}

const d = {
	'0': 't',
	'1': 'a',
	'2': 'o',
	length: 3
}


var itD = d[Symbol.iterator]();




console.log(itD.next());
console.log(itD.next());
console.log(itD.next());
console.log(itD.next());

你可能感兴趣的:(javascript)