首页 > 解决方案 > 将变量分配为数组中的键

问题描述

我想初始化数组时遇到问题。所以基本上我使用库 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 显示为别名,而不是它们的值。

标签: angulartypescript

解决方案


之所以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);


推荐阅读