我有一个用打字稿写的类,在某些时候我想清除类成员变量。我如何在打字稿中做到这一点。
export Class Example{
storeNames: [] = [];
storeAddress: [] = [];
constructor(){
this.storeNames = ['mike','nelson'];
this.storeAddress = ['US','UK'];
}
clearData(){
//here i want to clear those variables, but not in old fashion way,
//I meant assigning them again empty array (this i don't want, because if there are 10 variables then i have to clear them in this method, which is more inefficient way (i feel)
}
}
答案 0 :(得分:2)
这里实际上没有任何魔术,您只需执行您不想执行的操作,并为其分配新值即可。最简单,最清晰的方法就是处理无聊的旧作业:
this.storeNames = [];
this.storesAddress = [];
// ...
您可以使用循环结构和动态属性名称访问,但是不清楚:
for (const name of ["storeNames", "storeAddress"]) {
this[name] = [];
}
旁注:storeNames
和storeAddress
这两个属性的名称建议您将数据存储在并行数组中(storeNames[0]
是{{1} }等)。通常,这不是最佳实践。而是存储一个存储对象数组:
storeAddress[0]
这还具有一次分配即可清除整个商店的优势。