简体   繁体   English

Javascript如果不是速记的话则一行混淆

[英]Javascript one line if else shorthand confusion

var type = ''; // type is from somewhere
if(type == 'a'){
type = 1;
}else{
type = 2;
}

How to simplify above if else statement using JS shorthand? 如何使用JS速记简化上述if else语句?

我不确定“ JS简写”是什么意思,但也许您正在寻找三元条件运算符

type = (type == 'a') ? 1 : 2;

You can use the ternary operator, also called the conditional operator, inline if (iif), or ternary if. 您可以使用三元运算符(也称为条件运算符),内联if(iif)或三元if。 In your example, this would look like the following: 在您的示例中,它看起来如下所示:

type = type == 'a' ? 1 : 2;

More info on Wikipedia: http://en.wikipedia.org/wiki/%3F: 有关Wikipedia的更多信息: http://en.wikipedia.org/wiki/%3F:

除了三元数之外,您还有更多选择,尤其是考虑到1不是虚假的时

type = {'a': 1}[type] || 2;

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

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