JS - 三元运算符,以避免条件中的过多链接。可能吗?

问题描述 投票:0回答:1
condition ?
    domElement.classList.add('show') :
    domElement.classList.remove('show');

上面的代码可以工作,但DOM变量和classList被显式输入两次。有没有办法使用三元组只将链中的差异部分放在各自的真/假条款中?

我想的是:

domElement.classList condition ? .add('show') : .remove('show');

任何和所有输入都非常感谢。

javascript ternary-operator code-duplication method-chaining
1个回答
8
投票
domElement.classList[condition ? 'add' : 'remove']('show')

更好但是​​:

domElement.classList.toggle('show', condition)

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Methods

© www.soinside.com 2019 - 2024. All rights reserved.