gpt4 book ai didi

javascript - typescript :将方法添加到类的数组

转载 作者:行者123 更新时间:2023-11-30 11:14:33 25 4
gpt4 key购买 nike

假设我有一个 Article 模型,其中有一个字段包含不同语言的文章名称:

class Article {
constructor(public name: Translation[]) { }
}

class Translation {
constructor(
public language: string,
public text: string
) { }
}

我希望能够调用一个方法将该文章名称翻译成作为参数给定的语言:

article.name.translate('EN')

如何将该方法添加到该翻译数组?

最佳答案

V1:

class Article {
constructor(public name: Translation[]) { }

public translate(language:string):string {
return this.name.find(t=>t.language==language).text;
}
}


class Translation {
constructor(
public language: string,
public text: string
) { }
}

let a = new Article([
new Translation('EN', 'Yes'),
new Translation('DE', 'Ja')
]);
a.translate('EN');

V2:

class Article {
constructor(public name: TranslatableProperty) { }
}

class TranslatableProperty {
constructor(public propTranslation:Translation[]) { }

public translate(language:string):string {
return this.propTranslation.find(t=>t.language==language).text;
}

}

class Translation {
constructor(
public language: string,
public text: string
) { }

}

let a = new Article(new TranslatableProperty([
new Translation('EN', 'Yes'),
new Translation('DE', 'Ja')
]));
a.name.translate('EN');

关于javascript - typescript :将方法添加到类的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52147543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com