【发布时间】:2020-04-21 01:16:26
【问题描述】:
我有一个带有 2 个私有属性和一个对象数组的 typescript 类。
class AssigningProperties {
private animalType1: string;
private animalType2: string;
animals = [
{
name: "Bob",
type: "cat"
},
{
name: "Max",
type: "dog"
}
];
constructor() {
this.animals.forEach(v => console.log(v.name));
}
}
new AssigningProperties ();
我想将类属性animalType1 分配给cat 和animalType2 分配给dog,最好使用Array.foreach。
我可以使用对象的索引来分配它,如下所示:
this.animalType1 = this.animals[0].type; 但我觉得有更好的方法。帮忙?
【问题讨论】:
-
“我想将类属性
animalType1分配给cat...” 次要术语nitpick:“类属性”通常表示static属性(aAssigningProperties的属性,构造函数)。animalType1是一个 instance 属性。
标签: arrays typescript object foreach