溫溫醬
2021-06-15 13:00:53
說我有一堂課Class A {}并且想要遍歷Class A屬性(檢查空值)只知道Class A將具有屬性但可能在屬性名稱和屬性數(shù)量上有所不同(例如)Class A { A: string; B: string;} 或者Class A { B: string; C: string; D: string;}有沒有辦法遍歷Class A屬性并檢查值是否為空?
2 回答

慕雪6442864
TA貢獻1812條經(jīng)驗 獲得超5個贊
在運行時
僅當(dāng)您明確分配它們時。
class A {
B: string | null = null;
C: string | null = null;
D: string | null = null;
}
const a = new A();
for (let key in a) {
if (a[key] == null) {
console.log('key is null:', key);
}
}

紅顏莎娜
TA貢獻1842條經(jīng)驗 獲得超13個贊
TypeScript 類在運行時不存在,因為它被轉(zhuǎn)換為普通的舊 JavaScript。您可以獲取對象實例的屬性
const a = { prop1: null, prop2: 'hello', prop3: 1 };
const nullProps = obj => Object.getOwnPropertyNames(obj).filter(prop => obj[prop] === null);
console.log(nullProps(a));
添加回答
舉報
0/150
提交
取消