问题描述
我一直在寻找创建具有附加功能的自己的打字稿数组的方法。 我碰到了这篇文章: To post
他们建议按照以下方法创建列表类
class List<T> {
public items: Array<T>;
constructor() {
this.items = [];
}
size(): number {
return this.items.length;
}
add(value: T): void {
this.items.push(value);
}
get(index: number): T {
return this.items[index];
}}
一切正常。 唯一的问题是当我将列表分配给另一个要从列表中获取数组的引用时。我总是必须添加项目参考。
示例
myList:List<string> = new List();
ArrayItems = myList.items;
打字稿中是否有一种方法可以确定使用equals(=)运算符时将返回什么?
解决方法
我对此进行了更深入的研究,发现以下代码有效
export class List<T> extends Array<T> {
constructor(array:Array<T> = []) {
super();
for(let i=0; i<array.length; i++)
this.add(array[i])
}
size(): number {
return this.length;
}
add(value: T): void {
this.push(value);
}
public clear(){
this.splice(0,this.length);
}
}
现在,我可以使用new创建一个List对象,并使用默认构造函数或在构造函数括号中添加一个数组。
当我现在想要数组时,我可以引用列表Object。 我猜Typescript会自动选择我要扩展的数组。
private myList:List<string>;
private arrayTest[];
public Init()
{
this.myList= new List(); //Default constructor
this.myList= new List(["A","B","C"]); //Constructor with params
this.arrayTest = this.mysList; //Selects automatically the array
}
构造函数中的代码使此List对象引用正确的数组数据。向Array的超级构造函数填充参数会创建一个新对象,并且无法100%正确地工作super(...array)
希望这对某人有用。