angular - 将变量分配为数组中的键
问题描述
我想初始化数组时遇到问题。所以基本上我使用库 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 显示为别名,而不是它们的值。
解决方案
之所以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);
推荐阅读
- angular - Jasmine + Angular中的模拟“窗口”对象
- opencv - Solvepnp CPP 函数给出不同的结果
- angular - 如何循环嵌套的json响应打字稿Angular 2
- angular - 我想在 Angular 6 中切换菜单
- sql - Oracle FULL OUTER JOIN 三张表有两个条件
- javascript - webpack从js文件捆绑多个css导入
- python - Tkinter 使用网格几何管理器动态更改小部件位置
- c - C. 将结构字段的第一个字符与循环中的数组元素进行比较。SIGSEGV
- c++ - 分解模板参数包操作
- ios - 使用 DispatchSemaphore wait() 冻结应用程序