gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 21:52:23 32 4
gpt4 key购买 nike

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

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 函数,而且它是一个有点 Yoda 条件,但也可以写成

typeof popup_window.close === "function"

所以 popup_window 必须有一个 close 方法才能继续下一步。最后一步关闭弹出窗口,如果它不为空,并且它有一个 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com