JS if/else速记的快速翻译

Quick translation of JS if/else shorthand?

本文关键字:翻译 JS else if      更新时间:2023-09-26

如果我能看到这些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"))}

无论你做什么,都不要这样写代码,如果你发现代码是这样写的,就修复它。你会被它弄糊涂,因为它很令人困惑。不是你。:-)

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

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"