如何在对象内部使用三元运算符简化Option元素创建逻辑?
I have this existing ternary operator code:
[',' , '|' , ';' , 'TAB'].forEach(separator => separatorSelect.append($('<option>', separator === 'TAB' ? {value: ' ', text: separator} : {value: separator, text: separator})));When
separatoris 'TAB', the object'svalueis 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
separatorequals 'TAB' - If the condition is true, it returns the tab character (
) as thevalueproperty - If false, it uses the original
separatorstring as thevalue
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

