繁体   English   中英

将变量指定为Array中的键

[英]Assign a variable as key in an Array

我想要初始化数组时遇到问题。 所以基本上我使用库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); 

暂无
暂无

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

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