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

如何在对象内部使用三元运算符简化Option元素创建逻辑?

Can I use a ternary operator inside an object literal to conditionally set a property value?

I have this existing ternary operator code:

[',' , '|' , ';' , 'TAB'].forEach(separator => separatorSelect.append($('<option>', separator === 'TAB' ? {value: '	', text: separator} : {value: separator, text: separator})));

When separator is 'TAB', the object's value is set to a tab character ( ), and the code works fine. But I'm wondering if I can use a ternary operator inside the object literal instead of repeating the entire object structure, writing it like {value: 'ternary here?', text: separator}. Is this approach feasible?

Absolutely! This is totally feasible and actually a much cleaner way to write your code—you don’t need to duplicate the entire object just to adjust one property value. You can directly use the ternary operator as the value for the value key within your object literal.

Here’s how you’d refactor your code:

[',' , '|' , ';' , 'TAB'].forEach(separator => 
  separatorSelect.append($('<option>', {
    value: separator === 'TAB' ? '	' : separator,
    text: separator
  }))
);

Here’s the breakdown:

  • The ternary operator checks if separator equals 'TAB'
  • If the condition is true, it returns the tab character ( ) as the value property
  • If false, it uses the original separator string as the value

This keeps your code DRY (Don’t Repeat Yourself) and boosts readability by cutting out redundant object structure. JavaScript fully supports using expressions like ternaries as values in object literals—any valid expression that resolves to a value can be assigned directly to an object property this way.

内容的提问来源于stack exchange,提问作者Kevin.a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:48:37