说我有一堂课Class A {}并且想要遍历Class A属性(检查空值)只知道Class A将具有属性但可能在属性名称和属性数量上有所不同(例如)Class A { A: string; B: string;} 或者Class A { B: string; C: string; D: string;}有没有办法遍历Class A属性并检查值是否为空?
2 回答

慕雪6442864
TA贡献1812条经验 获得超5个赞
在运行时
仅当您明确分配它们时。
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条经验 获得超12个赞
TypeScript 类在运行时不存在,因为它被转换为普通的旧 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
提交
取消