Javascript Curly支持奇怪的行为

Max*_*s S 0 javascript jquery

在下面的代码中,

    if (options.max) {
        if (i <= options.max) $(x).addClass("hey");
    }
    else {
        if (i >= options.min) $(x).addClass("no"); //<- this
    }
Run Code Online (Sandbox Code Playgroud)

从上面删除每个花括号使第二个子句(标记为<- this)不起作用.

    if (options.max)
        if (i <= options.max) $(x).addClass("hey");
    else
        if (i >= options.min) $(x).addClass("no"); //<- this
Run Code Online (Sandbox Code Playgroud)

我认为JavaScript中的if语句的单个表达式可以在没有花括号的情况下使用.为什么会这样?

小智 5

如果删除花括号,则else适用于第二个if,即:

if (options.max)
    if (i <= options.max) $(x).addClass("hey");
    else
        if (i >= options.min) $(x).addClass("no"); //<- this
Run Code Online (Sandbox Code Playgroud)

花括号需要确保将其else应用于整个语句,但是可以删除第二组,即:

if (options.max) {
    if (i <= options.max) $(x).addClass("hey");
}
else
    if (i >= options.min) $(x).addClass("no"); //<- this
Run Code Online (Sandbox Code Playgroud)

另一种方法是用&&运算符替换内部if语句,如下所示.

if (options.max)
    i <= options.max && $(x).addClass("hey");
else
    i >= options.min && $(x).addClass("no");
Run Code Online (Sandbox Code Playgroud)

注意:这是有效的,因为如果操作数之前&&等于false ,表达式将"短路" .