【问题标题】:Enumerate properties on an object枚举对象的属性
【发布时间】:2017-03-05 06:14:15
【问题描述】:

给定以下类,我如何枚举它的属性,即获得像 [station1, station2, station3 ...] 这样的输出?

我只能看到如何枚举属性的值,即[null, null, null]

class stationGuide {
    station1: any;
    station2: any;
    station3: any;

    constructor(){
        this.station1 = null;
        this.station2 = null;
        this.station3 = null;
     }
}

【问题讨论】:

    标签: typescript iterator


    【解决方案1】:

    您有两个选择,使用Object.keys(),然后使用forEach,或者使用for/in

    class stationGuide {
        station1: any;
        station2: any;
        station3: any;
    
        constructor(){
            this.station1 = null;
            this.station2 = null;
            this.station3 = null;
         }
    }
    
    let a = new stationGuide();
    Object.keys(a).forEach(key => console.log(key));
    
    for (let key in a) {
        console.log(key);
    }
    

    (code in playground)

    【讨论】:

    • 如果您想访问该值,则可以将其引用为console.log( a[key] )
    • 这两种选择有什么优缺点吗?
    • @MortimerCat 我没有检查基准,所以我不能肯定地说,但我不知道。这通常取决于您要做什么。
    • @MortimerCat 好吧,Object.keys 方法只会列出对象的直接属性,而不是继承的属性。但是for/in 也会遍历继承的属性。
    【解决方案2】:

    使用Reflect 对象,您可以以编程方式访问和修改任何对象。这种方法也不会抛出“元素隐式具有'any'类型,因为'string'类型的表达式不能用于索引类型'{}'”错误。

    class Cat {
      name: string
      age: number
    
      constructor(name: string, age: number){
        this.name = name
        this.age = age
       }
    }
    
    function printObject(obj: any):void{
      const keys = Object.keys(obj)
      const values = keys.map(key => `${key}: ${Reflect.get(obj,key)}`)
      console.log(values)
    }
    
    const cat = new Cat("Fluffy", 5)
    const dog = {
      name: "Charlie",
      age: 12,
      weight: 20
    }
    
    printObject(cat)
    printObject(dog)
    

    (code in playground)

    【讨论】:

    • Reflect.get(obj, key) 还是(obj as any)[key] 更好?有什么好处吗?
    • 在这种情况下,最好选择Reflect.get(obj, key),因为Object.keys(obj) 返回一个any[],而Reflect.get(obj, key) 不需要密钥是字符串。例如:dog[Object.keys(dog)[0]] 将产生以下错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{名称:字符串;年龄:数字;重量:数量; }'。在“{ name: string; 类型”上找不到带有“string”类型参数的索引签名;年龄:数字;重量:数量; }'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2019-06-30
    • 2022-12-17
    • 1970-01-01
    • 2017-07-12
    相关资源
    最近更新 更多