我正在尝试理解大量使用逗号分隔表达式的脚本。例如:
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/