javascript - 逗号分隔表达式可以用作 JavaScript 中的 if 语句吗?

标签 javascript comma-operator

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

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 语句吗?

最佳答案

这确实是一系列陈述

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不能为null。
其次,我们可以假设 popup_window 是另一个窗口,用 window.open 打开,因为它应该有一个 close 函数,并且它是一个有点尤达条件,但也可以写成

typeof popup_window.close === "function"

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

popup_window.close()

因此,要达到这一点,其他两个条件必须为真,必须有一个窗口,并且它必须有一个 close 方法,然后是 close 方法被调用,窗口被关闭。

然后是逗号。来自docs

The comma operator evaluates each of its operands (from left to right) and returns the value of the last operand.

我们有

("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;

}

关于javascript - 逗号分隔表达式可以用作 JavaScript 中的 if 语句吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443386/

相关文章:

javascript - 在 firebase web 中读取 child 的 child (javascript)

javascript - scrollTop offset() 无法在容器内使用 div 进行动画处理/正常工作

c - 函数参数中的逗号运算符

c - 如何在 C 中解析使用逗号运算符的复杂表达式?

c++ - 括号之间的两个字符串在 C++ 中用逗号分隔

javascript - 在哪里/如何添加自定义 js magento

javascript - 使用 React 组件创建 iframe 小部件

javascript - 当我获得特定的移动分辨率时如何删除一个 css 类并添加另一个

c++ - for循环中的逗号

c++ - 使运算符重载上下文特定