Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

Javascript || or operator with a undefinded variable

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:

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;

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?

--Thanks. Bryan

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That Opera article gives a poor description of what is happening.

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.

The "falsey" values in javascript are:

  • 0
  • null
  • undefined
  • NaN
  • "" (empty string)
  • false

So you can see that there are many cases in which x will be set to 10 besides just undefined.

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.

Quick example: http://jsfiddle.net/V76W6/

var v = 0;

var x = v || 10;

alert( x ); // alerts 10

Assign v any of the falsey values that I indicated above, and you'll get the same result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...