You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ngx-gauge的thresholds中用变量作为对象键?

解决ngx-gauge thresholds属性变量键名的问题

你遇到的这个问题是JavaScript对象字面量的常见小坑——直接写变量名作为对象键时,它会被当作字符串字面量处理,而不是读取变量的实际值。要让变量的值成为对象的键,你需要用到ES6的计算属性名语法。

修正后的代码

const level1 = manager.getLevelOne(); 
const level2 = manager.getLevelTwo(); 
const level3 = manager.getLevelThree(); 

// 使用方括号包裹变量,解析变量值作为键
thresholds = {
  [level1]: { color: 'red' }, 
  [level2]: { color: 'green' }, 
  [level3]: { color: 'orange' }
};

原理说明

用[level1]这种写法时,JavaScript会先计算level1变量的实际值,再把这个值作为对象的键,而不是把字符串'level1'当作键。现在你再执行console.log(thresholds),就能看到对象的键是从manager获取到的真实数值了。

兼容旧环境的替代方案

如果你的项目环境不支持ES6+语法(不过Angular项目一般都支持),可以用先创建空对象再逐个赋值的方式:

const level1 = manager.getLevelOne(); 
const level2 = manager.getLevelTwo(); 
const level3 = manager.getLevelThree(); 

const thresholds = {};
thresholds[level1] = { color: 'red' };
thresholds[level2] = { color: 'green' };
thresholds[level3] = { color: 'orange' };

内容的提问来源于stack exchange,提问作者Observablerxjs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:40:23