通过用于排序

时间:2016-07-26 13:06:21

标签: typescript

问题很简单,在javascript中我可以拥有一个像这样的对象

var obj={
    par1:'value1',
    par2:'value2'
}

我可以通过这种方式访问​​这些值obj['par1']是否可以使用类似这样的类在TypeScript中执行相同的操作:

export class obj{
    par1:string;
    par2:string;
}

this.obj['par1']=value1

更新

这是文档

export class Documents {
    par1: string
    par2: string
    constructor(par1: string,
        par2: string
    ){
        this.par1=par1
        this.par2=par2
    }
}

这是我的尝试:

private docs:Documents[]=new Documents[
    new Documents('value1','value2'),
    new Documents('value3','value4')
];
sort(ordertype:string,property:string){
    for(let doc of this.docs){
        for(let field in doc)
            console.log(doc[field])
    }
}

这是一个错误:

  

[ts]元素隐式具有“任意”类型,因为索引表达式的类型不是“数字”。

我甚至试图将它转换为字符串,但没有。

更新2

我看到了错误,我纠正了错误,上面的代码是正确无误的。

2 个答案:

答案 0 :(得分:1)

您没有正确创建getNativeData数组,它应该是这样的:

Documents

let docs: Documents[] = [];
docs.push(new Documents('value1', 'value2'));
docs.push(new Documents('value3', 'value4'));

如果您这样做,那么您的代码可以正常运行,请查看in playground

答案 1 :(得分:0)

尝试将console.log(doc[field])替换为console.log((doc as any)[field])