Javascript ||或具有未定义变量的运算符 [英] Javascript || or operator with a undefinded variable
问题描述
我最近一直在读一篇我读过的文章来自Opera。
I have been doing some reading lately one article I read was from Opera.
http://dev.opera.com/articles/view/javascript-best-practices/
在那篇文章中他们写道:
In that article they write this:
JavaScript
中的另一种常见情况是为$提供预设值b $ b变量如果未定义,例如
so:
Another common situation in JavaScript is providing a preset value for a variable if it is not defined, like so:
if(v){
var x = v;
} else {
var x = 10;
}
这个的快捷符号是
双管字符:
The shortcut notation for this is the double pipe character:
var x = v || 10;
出于某种原因,我无法让这个为我工作。是否真的可以检查是否定义了v,如果不是x = 10?
For some reason I cant get this to work for me. Is it really possible to check to see if v is defined, if not x = 10?
- 谢谢。
Bryan
--Thanks. Bryan
推荐答案
Opera文章对发生的事情描述不佳。
That Opera article gives a poor description of what is happening.
虽然 x
确实会得到 10 $ c的值$ c>如果
v
是 undefined
。如果 v
x
, 10
也是如此有任何falsey值。
While it is true that x
will get the value of 10
if v
is undefined
. It is also true that x
will be 10
if v
has any "falsey" value.
javascript中的falsey值为:
The "falsey" values in javascript are:
-
0
-
null
-
undefined
-
NaN
-
(空字符串)
-
false
0
null
undefined
NaN
""
(empty string)false
所以你可以看到很多情况下 x
将设置为 10
除了 undefined
。
So you can see that there are many cases in which x
will be set to 10
besides just undefined
.
这是一些文档,详细说明了逻辑运算符。 (这是逻辑OR。)它给出了几个用于这种赋值的例子。
Here's some documentation detailing the logical operators. (This one is the "logical OR".) It gives several examples of its usage for such an assignment.
快速示例:http://jsfiddle.net/V76W6/
var v = 0;
var x = v || 10;
alert( x ); // alerts 10
分配 v
任何我在上面指出的假值,你会得到相同的结果。
Assign v
any of the falsey values that I indicated above, and you'll get the same result.
这篇关于Javascript ||或具有未定义变量的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!