快速翻译JS if / else简写?

时间:2014-08-28 17:21:54

标签: javascript jquery css

如果我能看到这些if / else语句写得很长,那么这个轮播如何工作会变得有点容易理解。根据我的理解,if / else简写如下:

isThisTrue? thenDoThis: ifNotDoThis

但是当添加更多条件时,我会感到有些困惑。任何帮助将不胜感激。

n.attr("id")=="right"?currentIndex==$("#slider li").size()-1?currentIndex=0:currentIndex++:n.attr("id")=="left"?currentIndex==0?currentIndex=$("#slider li").size()-1:currentIndex--:currentIndex=n.attr("data-position");

SetTheme:function(n){n.hasClass("dark")?($("#logo").addClass("dark"),$("#ips").addClass("dark"),$("#nav").addClass("dark"), $("#but-links").addClass("dark"),$("#but-search").addClass("dark")):n.hasClass("light")&&($("#logo").removeClass("dark"),$("#ips").removeClass("dark"), $("#nav").removeClass("dark"), $("#but-links").removeClass("dark"), $("#but-search").removeClass("dark"))}

1 个答案:

答案 0 :(得分:4)

无论你做什么,都不要编写类似的代码,如果你发现这样的代码,请修复它。你很困惑,因为它令人困惑。不是你。 : - )

但规则是条件运算符的操作数是 greedy ,从左到右。让我们自己提醒条件运算符的三个操作数(就像你在问题中所做的那样):

operand1 ? operand2 : operand3

因为操作数是贪婪的,这意味着,例如:

val = true  ? true ? "a" : "b" : "c"; // is "a"
val = false ? true ? "a" : "b" : "c"; // is "c"
//          ^ ^^^^^^^^^^^^^^^^
//          | \              /
//          |  \            /
//          |   +----------+--- this is operand2 to...
//          +------------------ this conditional operator

...因为它们等同于

val = true  ? (true ? "a" : "b") : ("c"); // is "a"
val = false ? (true ? "a" : "b") : ("c"); // is "c"
相关问题