[英]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.