admin管理员组文章数量:1387447
I saw a piece of code that stuck me as odd. What does switch(!0) mean in javascript? What are some cases where this technique would be useful to use?
jsTree uses it in a few places but it looks foreign. I'm sure it has a good reason behind it, but can't figure it out.
/
Here is a clip of code:
switch(!0) {
case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
case ($.isFunction(s.data)): //...
break;
}
I saw a piece of code that stuck me as odd. What does switch(!0) mean in javascript? What are some cases where this technique would be useful to use?
jsTree uses it in a few places but it looks foreign. I'm sure it has a good reason behind it, but can't figure it out.
http://www.jstree./
Here is a clip of code:
switch(!0) {
case (!s.data && !s.ajax): throw "Neither data nor ajax settings supplied.";
case ($.isFunction(s.data)): //...
break;
}
Share
Improve this question
asked Aug 10, 2012 at 23:37
MMeahMMeah
1,0421 gold badge9 silver badges18 bronze badges
4
-
2
Someone is trying to obfuscate their code I'd say. This is a hacky way to not use
if
andif else
. – Torsten Walter Commented Aug 10, 2012 at 23:41 - possible duplicate of What does !1 and !0 mean in Javascript? – user1106925 Commented Aug 11, 2012 at 0:00
- 1 Because sensical code is too mainstream. Also, I say we should name these Yoda switches. – Mahn Commented Aug 11, 2012 at 0:13
- @Mahn HA! I am for the new term. +1 the ment if you like the new term "Yoda switches" – MMeah Commented Aug 12, 2012 at 7:35
2 Answers
Reset to default 9It's paring each of the cases to boolean true
.
Elaborating
case (!s.data && !s.ajax)
If !s.data && !s.ajax
evaluates to true
, then this case will be selected for execution.
switch(true)
is the same as switch(!0)
A switch(!0)
is simply the same as switch(true)
.
This pattern:
switch (true) {
case (condition): do something; break;
case (condition): do something; break;
case (condition): do something; break;
}
Works the same as:
if (condition) {
do something;
} else if (condition) {
do something;
} else if (condition) {
do something;
}
本文标签: javascriptswitch(0) What does it meanStack Overflow
版权声明:本文标题:javascript - switch(!0) What does it mean - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744572263a2613412.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论