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

VueJS三元运算符多分支问题:新增代币后代码报错求助

问题解决:嵌套三元运算符语法错误修正

你的代码报错是因为嵌套三元运算符的语法使用错误,三元运算符的标准结构是 条件 ? 真值表达式 : 假值表达式,你在中间错误地用了第二个 ?,导致语法解析失败。

正确的嵌套三元写法

第一行代码修正:

// 简洁写法
const fetcher = currency === 'eth' ? fetchEthBalance : currency === 'usdt' ? fetchUsdtBalance : fetchArbBalance;

// 加括号明确优先级,可读性更强
const fetcher = currency === 'eth' 
  ? fetchEthBalance 
  : (currency === 'usdt' ? fetchUsdtBalance : fetchArbBalance);

第二行代码修正:

// 简洁写法
userStore[currency === 'eth' ? 'balanceEth' : currency === 'usdt' ? 'balanceUsdt' : 'balanceArb'] = balance;

// 加括号明确优先级
userStore[currency === 'eth' 
  ? 'balanceEth' 
  : (currency === 'usdt' ? 'balanceUsdt' : 'balanceArb')] = balance;

更优的替代方案:用对象映射代替嵌套三元

嵌套三元在条件增多后会变得难以阅读和维护,推荐用对象映射的方式实现,逻辑更直观,后续新增代币也更方便:

处理 fetcher:

// 定义映射关系
const fetcherMap = {
  eth: fetchEthBalance,
  usdt: fetchUsdtBalance,
  arb: fetchArbBalance
};
// 根据currency取值,默认用fetchArbBalance兜底
const fetcher = fetcherMap[currency] || fetchArbBalance;

处理 userStore 余额属性:

// 定义键名映射
const balanceKeyMap = {
  eth: 'balanceEth',
  usdt: 'balanceUsdt',
  arb: 'balanceArb'
};
// 根据currency设置对应余额,默认用balanceArb兜底
userStore[balanceKeyMap[currency] || 'balanceArb'] = balance;

这种写法的优势:后续新增其他代币(比如BTC),只需要在映射对象里添加对应的键值对,不需要修改复杂的条件判断,代码可读性和可维护性大幅提升。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:07