假设我有一堂这样的课:
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/