【问题标题】:Can comma separated expressions be used as if statement in Javascript?可以将逗号分隔的表达式用作 Javascript 中的 if 语句吗?
【发布时间】:2015-02-10 22:48:32
【问题描述】:

我试图理解大量使用逗号分隔表达式的脚本。例如:

popup_window != is_null && ("function" == typeof popup_window.close && popup_window.close(), popup_window = is_null);

如果逗号分隔的意思是“评估以下所有表达式,然后产生最终表达式的值”是真的(如this SO answer),这是另一种形式的 if 语句吗?

喜欢:
"如果 popup_window 不为 null 且 popup_window.close 是一个方法,则调用此方法并将 popup_window 设置为 null"

无论如何,我不确定我是否理解语法。

问题
这句话是什么意思,逗号分隔是怎么回事?这应该是一个 if 语句吗?

谢谢!

【问题讨论】:

  • 这只是使用 AND 来检查多个语句的一种聪明(太聪明)的方式,如果它们都是真实的,它会到达逗号用作运算符的末尾,如果 @ 987654324@返回truthy(如果存在则返回popup),变量popup_window设置为is_null,根据语句可能是null
  • 没错,就像if ( truthy && falsy && truthy ),最后一个永远不会被检查,因为第二个是假的,然后就失败了。
  • 这是一个编译后的缩小脚本。获取源代码,没有人会手写。
  • 当你写的时候: if( a() && b() && c() ) {} a() 将被测试,如果 a() 返回 true,b() 将被测试,如果b() 返回 true,c() 将在您编写时进行测试: if(a() && b() , c() ) {} a() 将被测试,如果 a() 返回 true b() 将是经过测试,c() 将始终被评估jsfiddle.net/try2d0rj
  • 我知道有人在写这样的代码——所以这不需要由 minifiers 生成;)

标签: javascript expression comma


【解决方案1】:

真的是一连串的陈述

popup_window != is_null // if true, continue to the statement in the parenthesis
    && 
(
    "function" == typeof popup_window.close // if true continue to close the window
      && 
    popup_window.close()
    , popup_window = is_null // this is executed as long as "popup_window != is_null" 
);                           // is truthy, it doesn't depend on the other conditions

假设is_null真的是null,首先popup_window不能为空。
其次,我们可以假设popup_window是另一个窗口,用window.open打开,因为它应该有一个close函数,这有点像尤达条件,但也可以写

typeof popup_window.close === "function"

所以popup_window 必须有一个close 方法才能继续下一步。 如果弹出窗口不为空,并且有close 方法,则最后一步关闭弹出窗口。

popup_window.close()

所以其他两个条件必须是真实的才能走到这一步,必须有一个窗口,它必须有一个close方法,然后调用close方法,然后关闭窗口.

然后是逗号。来自 docs

逗号运算符计算其每个操作数(从左到右) 并返回最后一个操作数的值。

我们有

("function" == typeof popup_window.close && popup_window.close(), popup_window = is_null);

让我们写得有点不同

(                          // ↓ must be thruthy .... ↓ for this to execute
   (typeof popup_window.close === "function" && popup_window.close())
   , popup_window = is_null
);      // ↑ unrelated, it's just another operand, seperated by comma

这里的诀窍是,逗号之后的最后一部分总是被执行,因为所有由逗号分隔的操作数都被计算了。

这意味着如果popup_window 不是is_null,则无论第二个条件如何,popup_window 都会显式设置为is_null

第二个条件也只是执行popup_window不是is_null,然后检查是否有close()方法,并关闭窗口,逗号后面的语句与该条件的结果无关.

写得更简单(IMO应该是这样写的)

if ( popup_window != is_null ) {

    if ( typeof popup_window.close === "function" ) {
        popup_window.close();
    }

    popup_window = is_null;

}

【讨论】:

  • 出色的答案。谢谢!
猜你喜欢
  • 2017-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-02
相关资源
最近更新 更多