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

如何使对象 iterable 化, 以其可以支持 for...of 迭代 #20

Open
yanlele opened this issue Mar 4, 2023 · 0 comments
Open
Labels
JavaScript JS 基础语法
Milestone

Comments

@yanlele
Copy link
Owner

yanlele commented Mar 4, 2023

在 JavaScript 中,如果一个对象要被 for...of 迭代,那么它必须是可迭代的。可迭代对象是一种具有 Symbol.iterator 方法的对象,该方法返回一个迭代器对象,该迭代器对象实现了 next() 方法,每次调用 next() 方法都返回一个包含 value 和 done 属性的对象,用于迭代对象的每个元素。

因此,要使一个对象 iterable 化,需要实现一个 Symbol.iterator 方法。该方法应该返回一个迭代器对象,这个迭代器对象应该实现 next() 方法,用于返回迭代对象的每个元素。

举一个例子下面是一个简单的示例,演示如何将一个普通对象 iterable 化:

const myObj = {
  data: [1, 2, 3],
  [Symbol.iterator]() {
    let index = 0;
    return {
      next: () => {
        if (index < this.data.length) {
          return { value: this.data[index++], done: false };
        } else {
          return { done: true };
        }
      },
    };
  },
};

for (const item of myObj) {
  console.log(item);
}
// 输出:1, 2, 3

再举一个例子,比如我们有一个对象,里面存储了一些学生的信息,我们希望能够使用 for...of 循环遍历每个学生信息:

const students = {
  Alice: { age: 18, gender: 'female', score: 90 },
  Bob: { age: 19, gender: 'male', score: 85 },
  Charlie: { age: 20, gender: 'male', score: 95 }
};

students[Symbol.iterator] = function* () {
  const keys = Object.keys(this);
  for (let i = 0; i < keys.length; i++) {
    yield [keys[i], this[keys[i]]];
  }
};

for (const [name, info] of students) {
  console.log(`${name}: ${info.age} ${info.gender} ${info.score}`);
}

这样我们就可以使用 for...of 循环遍历学生信息对象中的每个学生信息了。

@yanlele yanlele added the JavaScript JS 基础语法 label Mar 4, 2023
@yanlele yanlele added this to the milestone Mar 5, 2023
@yanlele yanlele changed the title 【中】如何使对象 iterable 化, 以其可以支持 for...of 迭代 如何使对象 iterable 化, 以其可以支持 for...of 迭代 Mar 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JavaScript JS 基础语法
Projects
None yet
Development

No branches or pull requests

1 participant