不是布尔值,而是使用|| [英] not boolean value but use ||
问题描述
下面的代码获取不同浏览器中的窗口大小.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>
</body>
</html>
我想问window.innerWidth或document.documentElement.clientWidth等.它们不是布尔值,如何使用||声明一个变量? w/h是数字,就像我执行以下操作一样:
var k = aaa || bbb || 45;
k应该是数字,这是非法的,对吧? 那么第一段代码如何工作? 谢谢〜
这是由于 truthy 值Javascript.
如果在布尔上下文中使用它们,则 0
,null
和undefined
都将评估为false
.因此,您可以像上面那样进行赋值-var k
的值将是第一个真实的变量.
var k = aaa || bbb || 45;
如果aaa
是真实值(因此,是一个数字或某个定义的值),则k
变为该值,或者如果b
是真实值,则它变为b
,否则它变为数字45
.>
the below code get the window size in different browsers.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>
</body>
</html>
I want to ask window.innerWidth OR document.documentElement.clientWidth etc.. they are not Boolean values, how can I use || to declare a variable? w/h are numbers, it's like if I do the following:
var k = aaa || bbb || 45;
k is supposed to be a number, this is illegal, right? How can the first piece of code work then? Thanks~
It's because of the concept of falsy and truthy values in Javascript.
0
, null
and undefined
all evaluate to false
if you use them in a boolean context. So that allows you to make assignments like the above- the value of var k
will be the first variable that is truthy.
var k = aaa || bbb || 45;
If aaa
is truthy(so, a number, or some defined value), then k
becomes that, OR it becomes b
if that is truthy, otherwise it becomes the number 45
.
这篇关于不是布尔值,而是使用||的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!