代码之家  ›  专栏  ›  技术社区  ›  Sumchans

以结构化方式将项目推送到typescript中的数组

  •  0
  • Sumchans  · 技术社区  · 6 年前

    我这里有这些项目,我想把它们以一种固定的格式推送到一个数组中。 我已经这样声明了我的数组

    finalCount = [];
    

    现在,我希望此数组中包含以下格式的项: 动物:伯爵 例如: 狗:3只 猫:4只 奶牛:1头

    数组中的每一项都应该可以通过提供索引号来访问。例如,finalCount[0]应该选择dog。 我试着这样推东西

    this.finalCount.push(this.animal, this.count);
    

    但这里的每一项都不配套。 我怎么知道。

    1 回复  |  直到 6 年前
        1
  •  1
  •   maxletou    6 年前

    要在最终计数阵列中推送项目,您可以利用最初随ES2015推出的synthax, computed properties

    现在,如果要为finalCount数组中的对象定义TypeScript类型。您应该创建以下界面:

    interface FinalCountItem {
        [animal: string]: number;
    }
    
    finalCount: FinalCountItem[] = [];
    
    this.finalCount.push({[this.animal]: this.count});