如何返回一个迭代对象

function * foo() {
	yield 'Hello world';
}

const iter = foo();
console.log(iter);

Untitled

yield(产出),每次暂停函数执行,有记忆功能

function * foo() {
	console.log(1);
  yield 'Hello';
  console.log(2);
  yield 'world';
  console.log(3);
  return '!!!';
}

const iter = foo();

console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());

Untitled

return 会结束函数执行

function * test() {
	yield 'a';
  yield 'b';
  yield 'c';
  return 'd'
}
var iter = test();
console.log(iter);
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
console.log(iter.next()); // return 返回
console.log(iter.next());

Untitled

⭐️ yield 本身不产出值

function * test() {
	var a = yield 'a';
  console.log('a==>>', a);
  return 'd'
}
var iter = test();
console.log(iter);
console.log(iter.next());
console.log(iter.next());

Untitled

yield 的值可以通过 next 函数指定

function * test(){
	var a = yield 'a';
  console.log('a==>>', a);
  return 'd'
}
var iter = test();
console.log(iter);
console.log(iter.next(10));
console.log(iter.next(20));

Untitled

yield 在表达式中,要用括号括起来充当表达式

function * demo() {
	console.log('hello' + (yield 123));
}

yield 作为参数

function * demo(){
	foo(yield 'a', yield 'b');
}
function foo(a, b){
	console.log(a, b);
}
var iter = demo();
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());

Untitled