问题很简单,在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]元素隐式具有“任意”类型,因为索引表达式的类型不是“数字”。
我甚至试图将它转换为字符串,但没有。
我看到了错误,我纠正了错误,上面的代码是正确无误的。
答案 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])