mar*_*ibi 6 collections set typescript angular
我是 angular2 和打字稿的新手。我在创建像 Set<> 这样的独特集合时遇到了问题。我想避免集合中的重复对象,为此,尝试使用如下代码设置的数据类型:
private cardItems = new Set<MyBean>([]);
Run Code Online (Sandbox Code Playgroud)
MyBean 是一个对象。
export class MyBean {
id:integer
ownerId:integer
ownerName:string
img: string;
constructor() {
}
public equals(obj: MyBean) {
console.log(obj.id);
if (this.id == obj.id) {
console.log(obj.id);
return true;
}
if (obj == null)
return false;
return true;
}
public hashCode(obj: MyBean) {
return obj.id
}
Run Code Online (Sandbox Code Playgroud)
}
但 equals 和 hashCode 不会以这种方式运行。我在集合中有重复的对象。
实现 Set 的解决方案是什么?
非常感谢
如何扩展Set类然后覆盖add方法:
interface SetItem {
equals(other: SetItem): boolean;
}
class MySet<T extends SetItem> extends Set<T> {
add(value: T): this {
let found = false;
this.forEach(item => {
if (value.equals(item)) {
found = true;
}
});
if (!found) {
super.add(value);
}
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
(操场上的代码)
Set的实现方案是什么
JavaScriptSet使用与 JavaScript 类相同的算法,===并且无法覆盖JavaScript 类中的算法。
您可以使用利用可重写函数的东西,例如https://github.com/basarat/typescript-collections use toString。
| 归档时间: |
|
| 查看次数: |
13175 次 |
| 最近记录: |