问题
I know that in php 5.3 instead of using this redundant ternary operator syntax:
startingNum = startingNum ? startingNum : 1
...we can use a shorthand syntax for our ternary operators where applicable:
startingNum = startingNum ?: 1
And I know about the ternary operator in javascript:
startingNum = startingNum ? startingNum : 1
...but is there a shorthand?
回答1:
var startingNumber = startingNumber || 1;
Something like that what you're looking for, where it defaults if undefined?
var foo = bar || 1; // 1
var bar = 2;
foo = bar || 1; // 2
By the way, this works for a lot of scenarios, including objects:
var foo = bar || {}; // secure an object is assigned when bar is absent
回答2:
||
will return the first truthy value it encounters, and can therefore be used as a coalescing operator, similar to C#'s ??
startingNum = startingNum || 1;
回答3:
Yes, there is:
var startingNum = startingNum || 1;
In general, expr1 || expr2
works in the following way (as mentioned by the documentation):
Returns
expr1
if it can be converted totrue
; otherwise, returnsexpr2
. Thus, when used withBoolean
values,||
returnstrue
if either operand istrue
; if both arefalse
, returnsfalse
.
回答4:
var startingNum = startingNum || 1;
In this case, you can use the OR operator.
回答5:
startingNum = startingNum || 1
If you have a condition with null, like
startingNum = startingNum ? startingNum : null
you can use '&&'
startingNum = startingNum && startingNum
回答6:
The above answers are correct. In JavaScript, the following statement:
startingNum = startingNum ? otherNum : 1
can be expressed as
startingNum = otherNum || 1
Another scenario not covered here is if you want the value to return false when not matched. The JavaScript shorthand for this is:
startingNum = startingNum ? otherNum : 0
But it can be expressed as
startingNum = startingNum && otherNum
Just wanted to cover another scenario in case others were looking for a more generalized answer.
回答7:
To make a ternary like:
boolean_condition ? true_result : false_result
in javascript, you can do:
(boolean_condition && true_result ) || false_result;
Example:
(true && 'green') || 'red';
=> "green"
(false && 'green') || 'red';
=> "red"
来源:https://stackoverflow.com/questions/8884071/javascript-shorthand-ternary-operator