将变量指定为Array中的键

时间:2018-05-28 18:59:27

标签: angular typescript

我想要初始化数组时遇到问题。因此,基本上我使用库ngx-gauge在我的应用程序中显示仪表,其中一个属性是阈值,根据值有三种不同的颜色。例如: thresholds = {'0' : {color:'red'}, '100' : {color:'green'}, '200': {color:'orange'}};

我的问题是我想要代替' 0'' 100'和' 200'一个变量。我试图做的是:

const level1 = manager.getLevelOne();
const level2 = manager.getLevelTwo();
const level3 = manager.getLevelThree();
thresholds ={ level1 : {color:'red'}, level2:{color:'green'}, level3:{color:'orange'}};

然而,当我在console.log阈值时,它将level1,2和3显示为别名而不是它们的值。

1 个答案:

答案 0 :(得分:3)

thresholds= { level1: {color: 'red'}}不起作用的原因是因为它等同于thresholds= { "level1": color: 'red'}}(带引号)。只要level1是合法标识符,这两个版本在JavaScript中是等效的,第二个版本清楚地说明了正在发生的事情。

const level1 = "0";
const level2 = "100";
const level3 = "200";
thresholds = {
  [level1]: {
    color: 'red'
  },
  [level2]: {
    color: 'green'
  },
  [level3]: {
    color: 'orange'
  }
};
console.log(thresholds);

相关问题