如何避免在JavaScript单行'if'语句中使用重复措词

问题描述 投票:0回答:2

我正在编写一些代码,发现这很烦人,经过一番研究后找不到答案。尽管效果很好,但必须写三遍this.className却很笨拙:

this.className != 'selected' ? this.className = 'selected' : this.className = 'unselected';

我发现这个作品..

this.className = (this.className != 'selected') ? 'unselected' : 'selected';

..但是我想知道是否有可能实现相同的功能,但是this.className只写了一次,类似于以下内容:

this.className = 'selected' ? 'unselected' : 'selected';

欢迎提出任何建议。

javascript
2个回答
1
投票

不,你不能。第二个在一般情况下差不多。您的第三个操作符将导致它always设置'unselected',因为'selected'是真实的,因此第二个操作数('unselected')的值将始终是结果。


-5
投票

是的,您可以这样写:

this.className = 'selected' ? 'unselected' : 'selected';

三元是这样的:

if this ? then that : else this other thing;

这里,如果this.className的值为selected,则它将取值为unselected。否则,它将取值selected

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