如何&&如果不在控制语句中,则在JavaScript中工作? [英] How && works in JavaScript if isn't in a control statement?
问题描述
最近我使用了一些JavaScript代码,我发现了这个:
Recently I was working with some JavaScript code and I found this:
<script type="text/javascript">
window.localStorage&&window.localStorage.clear();
</script>
我在网上进行了研究,但没有找到任何关于实际上'&& '运算符如果不在控制语句中则有效。
I did research around the web but didn't find anything about how actually that '&&' operator works if isn't in a control statement.
有人知道它是如何工作的吗?
Does anyone know how it works?
推荐答案
这与以下内容相同:
if(window.localStorage){
window.localStorage.clear();
}
&&
一看到 false
(或falsy)值就会短路。
The &&
short-circuits as soon as it sees a false
(or "falsy") value.
所以,如果 window.localStorage
是 false
(或falsy),它会停止。如果是真的,它会继续并运行 window.localStorage.clear()
。返回值被忽略。
So, if window.localStorage
is false
(or "falsy"), it stops. If it's true, it continues and runs window.localStorage.clear()
. The return value is ignored.
这篇关于如何&&如果不在控制语句中,则在JavaScript中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!