'&&' and '||' vs '? :'
Why would you u开发者_StackOverflow中文版se this syntax?
var myVar = myArray.length && myArray || myObject;
instead of
var myVar = myArray.length ? myArray : myObject;
Edit: I just had a thought that if in the case of the && || syntax both sides of the || evaluated to false, as you might expect if myObject was undefined or null, if false would be returned. But it isn't, the objects value undefined or null is returned.
true || true //true
true || false //true
false || true //true
false || false //false
Edit2:
!!(myArray.length ? myArray : myObject);
This does however return false if myObject is undefined or null
x && y || z is different than x ? y : z even if it "works" in the case presented.
Consider when y evaluates to a false-value (in the post y can't be a false-value when it is evaluated because it is dependent upon x and thus it "works" as expected).
Using ?: is the much better and more clear construct in this case. The only reason I can give for using the other syntax is "too much cleverness".
A ternary is the only correct thing to do here, unless you guarantee that myObject.name has a "true" value.
Consider
res = a ? b : c;
vs.
res = a && b || c;
What is the difference? The first does what it is supposed to. But the second tests a. If a is false, it gets c, as the ternary version.
But if a is true, it only gets b if this is true as well, if not, it gets c, what is not wanted at all.
Tastes vary. Maybe somebody just got in the habit of writing things like
var myName = myObject && myObject.name || "unknown";
and stuck with it even when a ternary would work as well.
http://jsperf.com/conditional-operators
It looks like you use && || when you want your code to go slower and you want to obfuscate it a little more :)
There's also a difference between what is going on.
foo && bar || foobar // if foo or bar is false, then foobar will be returned
foo?bar:foobar // the bar, or foobar, is decided solely on foo
If you wanted the ternary to act like the logical conditional it would be:
foo&&bar?bar:foobar
加载中,请稍侯......
精彩评论