【问题标题】:JS – Ternary operator to avoid excessive chaining in a conditional. Is it possible?JS – 三元运算符以避免条件中的过度链接。是否可以?
【发布时间】:2018-09-04 12:36:48
【问题描述】:
condition ?
    domElement.classList.add('show') :
    domElement.classList.remove('show');

上面的代码有效,但是 DOM 变量和 classList 被显式键入了两次。有没有办法使用三元组只将链的不同部分放在它们各自的真​​/假子句中?

我在想这样的事情:

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

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

【问题讨论】:

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

标签: javascript ternary-operator code-duplication method-chaining


【解决方案1】:
domElement.classList[condition ? 'add' : 'remove']('show')

更好:

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

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

【讨论】:

    猜你喜欢
    • 2017-08-30
    • 2019-10-08
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    • 2016-10-04
    • 2019-01-27
    • 2016-10-27
    相关资源
    最近更新 更多