Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 31 期(ECMAScript-作用域 闭包):模拟ES6 Generator #34

Open
wingmeng opened this issue Jun 13, 2019 · 0 comments
Open

第 31 期(ECMAScript-作用域 闭包):模拟ES6 Generator #34

wingmeng opened this issue Jun 13, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 13, 2019

题目:

请模拟实现 ES6 中的 Generator 函数

function generator(array) {
  // 你的代码
}

测试数据:

const arr = [
  {
    name: '张三',
    age: 18
  }, {
    name: '李四',
    age: 22
  }, {
    name: '王五',
    age: 30
  }
];

const it = generator(arr);

console.log(it.next());  // {value: {age: 18, name: "张三"}, done: false}
console.log(it.next());  // {value: {age: 22, name: "李四"}, done: false}
console.log(it.next());  // {value: {age: 30, name: "王五"}, done: false}
console.log(it.next());  // {value: undefined, done: true}

参考答案:

function generator(array) {
  let nextIndex = 0;

  return {
    next: function() {
      return nextIndex < array.length ?
      {value: array[nextIndex++], done: false} :
      {value: undefined, done: true};
    }
  }
}
@wingmeng wingmeng changed the title 第 31 期(CMAScript-作用域 闭包):模拟ES6 Generator 第 31 期(ECMAScript-作用域 闭包):模拟ES6 Generator Jun 14, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant