javascript - 允许使用 Array.from 将数据结构转换为数组

标签 javascript node.js class

假设我有一堂这样的课:

class Foo {

 constructor(){
  this.internalList = new Set([1,2,3])
 }

}

有什么方法我可以像这样实现:

class Foo {

 constructor(){
  this.internalList = new Set([1,2,3])
 }

 toArray(){   // add this method

     const ret = [];
     for(const v of this.internalList){
         ret.push(v);
     }
     return ret;
  }

}

这样我就可以调用它:

  const v = Array.from(new Foo());

是否有一些接口(interface)或方法可以实现,以便 Array.from 在我的类上工作?

最佳答案

您正在寻找的接口(interface)是 iteration ,其中Array.from用途。你可以简单地做

class Foo {
  constructor(){
    this.internalList = new Set([1,2,3])
  }
  [Symbol.iterator]() {
    return this.internalList.values();
  }
}

values method of the Set创建一个我们可以在此处使用的迭代器,但您也可以实现自定义迭代器。

关于javascript - 允许使用 Array.from 将数据结构转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57826307/

相关文章:

javascript - jsonwebtoken 中的有效负载错误

javascript - 选择复选框以过滤匹配所有选择的结果

javascript - jQuery 代码被忽略

javascript - jQuery包含多个字符串优化

node.js - Kubernetes 上 pod 中的 localhost

node.js - 如何获取 Redis 的 lpop 或 rpop 项的索引

node.js - 如何开发通过本地目录从另一个项目引用的 Node 库?

JavaScript : add hidden class on element

jQuery 根据选择框选项添加 css 类

c# - 程序集中类的顺序