[英]Using classList method in square brackets
Is the putting a classList method inside square brackets considered as good practice? 将classList方法放在方括号内是否被认为是一种好习惯? I mean, sometimes I prefer to do:
我的意思是,有时候我更喜欢这样做:
elem.classList[ifTrue ? 'add' : 'remove']('className');
as opposed to: 相对于:
if (ifTrue) {
elem.classList.add('className');
} else {
elem.classList.remove('className');
}
Also, does using brackets have any impact on the performance/speed of code execution? 另外,使用方括号是否会对代码执行的性能/速度产生影响?
Is the putting a classList method inside square brackets considered as good practice?
将classList方法放在方括号内是否被认为是一种好习惯?
There's nothing really wrong with it. 没什么错。 It's shorter, more concise, no code duplication.
它更短,更简洁,没有代码重复。 As you say, you sometimes prefer it - if you know when to use and when not, then it's fine.
如您所说, 有时您会更喜欢它-如果您知道何时使用和何时不使用,那就很好。 The factors are:
这些因素是:
ifTrue
, then I'd choose if-else. ifTrue
完成其他事情时,我将选择if-else。 On the other hand, the repetion of elem.classlist
and 'classname'
are not optimal either. elem.classlist
和'classname'
的elem.classlist
也不是最优的。 There is a completely different and much better third way though: Using the toggle
method of classlists . 但是,还有一种完全不同且更好的第三种方法:使用classlists的
toggle
方法 。 It does take a second parameter which does just what you want to do: 它确实需要第二个参数,它可以完成您想做的事情:
elem.classList.toggle('className', ifTrue);
It was just invented for this very common case! 它是为这种非常常见的情况而发明的! Admittedly, it's worse for readability as many developers don't know what
toggle
does. 诚然,由于许多开发人员不知道
toggle
是什么,因此可读性更差。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.