如何动态地将值添加到我的typescript数组?

时间:2017-09-25 16:00:24

标签: arrays angular typescript

我试图动态填充我的pieChartColors数组,以便最终我的数组看起来像这样:

public pieChartColors:Array<Color> = [
{
  backgroundColor: '#141C48'
},
{
  backgroundColor: '#FF0000'
},
{
  backgroundColor: '#EFEFEF'
},
...
]

我从一个空白数组开始,并尝试了几种不同的方法来添加值,但它们都没有工作(我的颜色值没有哈希符号存储):

public pieChartColors: Array<Color> = [];

public buildPieChart() {
...        
    for (let pie of pieData) {
      // none of these work
      this.pieChartColors.push(backgroundColor: '#'+pie.backgroundColor);
      this.pieChartColors.backgroundColor.push('#'+pie.backgroundColor);
      this.pieChartColors['backgroundColor'].push('#'+pie.backgroundColor);
    }
...
}

顺便说一下,pieData是一个我用数据库循环来处理backgroundColor值的对象。如果我在console.log中调试了pie.backgroundColor,则该值可用。

1 个答案:

答案 0 :(得分:1)

就像在JavaScript中一样:

this.pieChartColors.push({backgroundColor: '#'+pie.backgroundColor});