在typescript中访问可索引对象

时间:2017-06-28 07:16:05

标签: angular typescript

我宣布了以下indexable object个,其中包含Videokey标识的number模型列表。{/ 1}}。

component.ts

private videoItems : {[key: number]: Array<Video>};      // indexable object

constructor(private action: Action, private videoModel: Video) {}

我已在组件

中按以下方式分配了它
this.action.items.forEach(
            (item : Video) => {
                this.videoItems[item.idVideo] = Object.assign(new Video(),this.videoModel);
            }
        );

Video.model.ts

export class Video {

    private _idVideo : number;

    get idVideo (): number {
        return this._idVideo ;
    }

    set idVideo (value: number) {
        this._idVideo = value;
    }
}

如果我尝试访问videoItems this.videoItems[12],我会undefined。如果我像this.videoItems['12']那样访问它,我会正确获取video对象。我的问题是即使我已将密钥声明为number并且也设置为number,那么为什么我应该使用string来访问它?

1 个答案:

答案 0 :(得分:1)

JavaScript对象的密钥必须为strings or symbols。后者是最近的一个补充。数字被强制转换为字符串,因此这样的代码可以工作:

let x = {}
x[10] = 'foo';
console.log(x[10]); // Prints "foo"
console.log(x['10']); // Prints "foo"
x['20'] = 'bar';
console.log(x[20]); // Prints "bar"

在浏览器或节点中尝试一下,看看 的行为确实如此。在你的情况下,它并不奇怪。也许还有别的东西在继续?