Allow for zero
Short-circuit evaluation determines if the first value is falsey. If so, return the second value, as follows:
var x = y || z; // if y is falsey return z
Is there a way to disregard zero-values as being falsey when using short-circuit evaluation without resorting to if/else statements or ternary operators?
您可以将您的号码包裹到一个Number对象中并检查;
var x = new Number(0) || console.log("never gets printed");
console.log(parseInt(x));
//or
console.log(x.valueOf());
EDIT:
If z
is a number, you can maybe use a trick like this:
var x1 = Number(y===0 && '0' || y || z)
// or
var x2 = (y===0 && '0' || y || z)-0
var z = -1;
var y = 42;
var x = y || z;
var x1 = Number(y===0 && '0' || y || z)
var x2 = (y===0 && '0' || y || z)-0
console.log('x:',x, ' x1:',x1, ' x2:',x2);
var y = 0;
var x = y || z;
var x1 = Number(y===0 && '0' || y || z)
var x2 = (y===0 && '0' || y || z)-0
console.log('x:',x, ' x1:',x1, ' x2:',x2);
var y = null;
var x = y || z;
var x1 = Number(y===0 && '0' || y || z)
var x2 = (y===0 && '0' || y || z)-0
console.log('x:',x, ' x1:',x1, ' x2:',x2);
Edit: this uses a ternary operator, so if that's not what you're looking for, don't use this.
Of course this is another simple way to do it:
var x = y || y==0?0:z;
if y
is truthy, then x
is set to y
if y
is falsy, and y==0
, then x
is set to 0
if y
is falsy, and y!=0
, then x
is set to z
;
下一篇: 允许为零