Shorthand if/else statement Javascript

天涯浪子 提交于 2019-11-27 05:15:19

问题


I'm wondering if there's a shorter way to write this:

var x = 1;
if(y != undefined) x = y;

I initially tried x = y || 1, but that didn't work. What's the correct way to go about this?


回答1:


var x = y !== undefined ? y : 1;

Note that var x = y || 1; would assign 1 for any case where y is falsy (e.g. false, 0, ""), which may be why it "didn't work" for you. Also, if y is a global variable, if it's truly not defined you may run into an error unless you access it as window.y.


As vol7ron suggests in the comments, you can also use typeof to avoid the need to refer to global vars as window.<name>:

var x = typeof y != "undefined" ? y : 1;



回答2:


Another way to write it shortly

bePlanVar = !!((bePlanVar == false));

// is equivalent to

bePlanVar = (bePlanVar == false) ? true : false;

// and 

if (bePlanVar == false) {
    bePlanVar = true;
} else {
    bePlanVar = false;
}



回答3:


y = (y != undefined) ? y : x;

The parenthesis are not necessary, I just add them because I think it's easier to read this way.




回答4:


Other way is using short-circuit:

x = (typeof y !== 'undefined') && y || 1

Although I myself think that ternary is more readable.




回答5:


Here is a way to do it that works, but may not be best practise for any language really:

var x,y;
x='something';
y=1;
undefined === y || (x = y);

alternatively

undefined !== y && (x = y);


来源:https://stackoverflow.com/questions/9864634/shorthand-if-else-statement-javascript

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