ES6学习——迭代器(Iterators):迭代器接口应用示例

这篇文章我们来看看迭代器的一些基本应用例子。

前面给的一些例子都是用for-of循环,或者spread操作符来处理迭代器的,下面我先看看一个更直接的方法:

var arr = [1,2,3],iter1 = arr[Symbol.iterator]();
console.log(iter1.next());//Object {value: 1, done: false}
console.log(iter1.next());//Object {value: 2, done: false}
console.log(iter1.next());//Object {value: 3, done: false}
console.log(iter1.next());//Object {value: undefined, done: true}
console.log(iter1.next());//Object {value: undefined, done: true}


从上面的代码可以看到,我们可以直接获取迭代器,然后手工遍历,不需要借助其它操作和语法。然后接着看用普通的for以及while循环遍历迭代器:

var iter2 = arr[Symbol.iterator]();
for(var i = iter2.next();!i.done;(i=iter2.next())){
	console.log("for:",i);
}

var iter3 = arr[Symbol.iterator](),j;
while(!(j=iter3.next()).done){
	console.log("while:",j);
}

在看个用迭代器实现斐波那契数列:

var Fib = {
	[Symbol.iterator]() {
		var n1 = 1, n2 = 1;
		return {
			next() {
				var current = n2;
				n2 = n1;
				n1 = n1 + current;
				return { value: current, done: false };
			}
		};
	}
};

for (var v of Fib) {//数列是无限的,需要借助break跳出循环
	console.log( v );
	if (v > 50) break;
}

规范中并没有说next函数的参数,其实是可以传参的,只不过JS内置的那些操作符语法都忽略掉了next的参数,你自己定义的迭代器可以处理next函数的参数。

var tasks = {
	[Symbol.iterator]() {
		var steps = this.actions.slice();
		return {
			next(...args) {
				if (steps.length > 0) {
					let res = steps.shift()(...args);
					return { value: res, done: false };
				}
				else {
					return { done: true }
				}
			}
		};
	},
	actions: []
};

tasks.actions.push(
	function step1(x){
		console.log( "step 1:", x );
		return x * 2;
	},
	function step2(x,y){
		console.log( "step 2:", x, y );
		return x + (y * 2);
	},
	function step3(x,y,z){
		console.log( "step 3:", x, y, z );
		return (x * y) + z;
	}
);

var it = tasks[Symbol.iterator](),result;
result = it.next( 10 );
console.log(result.value);//20
it.next( 20, 50 );
result = it.next( 20, 50, 120 );
console.log(result.value);//1120
it.next();


*以上全部代码在Chrome 47下通过测试


你可能感兴趣的:(ES6,ES6)