Simple substitute of assignment operators of logical ones in JavaScript?

喜你入骨 提交于 2019-12-22 11:22:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!