简体   繁体   English

简写 if/else 语句 Javascript

[英]Shorthand if/else statement Javascript

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我最初尝试x = y || 1 x = y || 1 , but that didn't work. x = y || 1 ,但这没有用。 What's the correct way to go about this?解决这个问题的正确方法是什么?

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

Note that var x = y || 1;注意var x = y || 1; var x = y || 1; would assign 1 for any case where y is falsy (eg false , 0 , "" ), which may be why it "didn't work" for you.对于任何yfalse情况(例如false0"" ),都会分配1 ,这可能就是它“对您不起作用”的原因。 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 .此外,如果y是一个全局变量,如果它真的没有定义,你可能会遇到错误,除非你以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> :正如 vol7ron 在评论中建议的那样,您还可以使用typeof来避免将全局变量引用为window.<name>

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

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;
}
y = (y != undefined) ? y : x;

括号不是必需的,我只是添加它们,因为我认为这样更容易阅读。

Other way is using short-circuit:另一种方法是使用短路:

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

Although I myself think that ternary is more readable.虽然我自己认为三元更具可读性。

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);

Appears you are having 'y' default to 1: An arrow function would be useful in 2020:似乎您将“y”默认为 1:箭头函数在 2020 年很有用:

let x = (y = 1) => //insert operation with y here

Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.让'x' 是一个函数,其中'y' 是一个参数,如果它是一些空值或未定义的值,它将被分配一个默认值'1',然后用y 返回一些操作。

You can try if/else this shorthand method:你可以试试 if/else 这个速记方法:

// Syntax
if condition || else condition

// Example
let oldStr = "";
let newStr = oldStr || "Updated Value";
console.log(newStr); // Updated Value

// Example 2
let num1 = 2;
let num2 = num1 || 3;
console.log(num2);  // 2  cause num1 is a truthy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM