簡體   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