问题
JavaScript has assignment operators corresponding to arithmetic ones: +=, -=, *=, /=, %=.
JavaScript also has assignment operators corresponding to bitwise ones: <<=, >>=, >>>=, &=, ^=, |=.
But it doesn't have assignment operators corresponding to logical ones: ||=, &&=.
Then, I can't do things like
aVeryLongVariableIdontWantToRepeat ||= 1;
In this other question it's explained why JS Java doesn't have such operators. I guess it's the same for JS.
But I want to know if there is a simple way to emulate them, avoiding
aVeryLongVariableIdontWantToRepeat = aVeryLongVariableIdontWantToRepeat || 1;
回答1:
No, there isn't. I feel like there should be more to this answer, but really, that's it. The shortest version of a = a || x is ... a = a || x.
回答2:
It might help you to investigate writing your code using Coffeescript, which has the ||= operator available.
回答3:
There isn't a shorter way: a = a || 1 is the simplest way to do it.
However, to avoid unnecessary assignment of values (slightly at the expense of readability) you can also do a || ( a = 1).
JSFIDDLE
var a,b='x';
a || ( a = 1 );
b || ( b = 2 );
console.log( a + ', ' + b ); // Outputs "1, x"
来源:https://stackoverflow.com/questions/20752183/simple-substitute-of-assignment-operators-of-logical-ones-in-javascript