简体   繁体   English

将变量指定为Array中的键

[英]Assign a variable as key in an Array

I have an issue when I want to initialize an array. 我想要初始化数组时遇到问题。 So basically I'm using the library ngx-gauge to display gauges in my application and one of the attributes is thresholds to have three different colors depending of the value. 所以基本上我使用库ngx-gauge来显示我的应用程序中的仪表,其中一个属性是阈值,根据值有三种不同的颜色。 for example: thresholds = {'0' : {color:'red'}, '100' : {color:'green'}, '200': {color:'orange'}}; 例如: thresholds = {'0' : {color:'red'}, '100' : {color:'green'}, '200': {color:'orange'}};

My problem is that I want to put instead of '0','100' and '200' a variable. 我的问题是我想把“0”,“100”和“200”变成一个变量。 What I tried to do is: 我试图做的是:

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

However when I console.log thresholds it shows level1,2 and 3 as alias and not their value. 但是当我在console.log阈值时,它将level1,2和3显示为别名而不是它们的值。

The reason why thresholds= { level1: {color: 'red'}} does not work is because it is equivalent to thresholds= { "level1": color: 'red'}} (with quotes). thresholds= { level1: {color: 'red'}}不起作用的原因是因为它等于thresholds= { "level1": color: 'red'}} (带引号)。 The two versions are equivalent in JavaScript as long as level1 is a legal identifier, and the second version makes it clear what's going on. 只要level1是合法标识符,这两个版本在JavaScript中是等效的,第二个版本清楚地说明了正在发生的事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM