简体   繁体   English

如何在 JavaScript 中编写内联 IF 语句?

[英]How to write an inline IF statement in JavaScript?

How can I use an inline if statement in JavaScript?如何在 JavaScript 中使用内联if语句? Is there an inline else statement too?是否也有内联else语句?

Something like this:像这样的东西:

var a = 2;
var b = 3;

if(a < b) {
    // do something
}

You don't necessarily need jQuery.你不一定需要 jQuery。 JavaScript alone will do this.仅 JavaScript 就可以做到这一点。

var a = 2;
var b = 3;    
var c = ((a < b) ? 'minor' : 'major');

The c variable will be minor if the value is true , and major if the value is false .如果值为 true ,则c变量将是minor的,如果false true则为major变量。


This is known as a Conditional (ternary) Operator.这称为条件(三元)运算符。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator

有一个三元运算符,如下所示:

var c = (a < b) ? "a is less than b"  : "a is not less than b";

对于内联编写if语句,其中的代码应该只有一个语句:

if ( a < b ) // code to be executed without curly braces;

You can also approximate an if/else using only Logical Operators.您还可以仅使用逻辑运算符来近似 if/else。

(a && b) || c

The above is roughly the same as saying:上面说的大致相同:

a ? b : c

And of course, roughly the same as:当然,大致与以下内容相同:

if ( a ) { b } else { c }

I say roughly because there is one difference with this approach, in that you have to know that the value of b will evaluate as true, otherwise you will always get c .我粗略地说是因为这种方法有一个区别,因为您必须知道b的值将评估为真,否则您将始终得到c Bascially you have to realise that the part that would appear if () { here } is now part of the condition that you place if ( here ) { } .基本上,您必须意识到if () { here }出现的部分现在是您放置if ( here ) { }的条件的一部分。

The above is possible due to JavaScripts behaviour of passing / returning one of the original values that formed the logical expression, which one depends on the type of operator.由于 JavaScript 传递/返回形成逻辑表达式的原始值之一的行为,上述情况是可能的,这取决于运算符的类型。 Certain other languages, like PHP, carry on the actual result of the operation ie true or false, meaning the result is always true or false;某些其他语言,如 PHP,会进行实际的运算结果,即 true 或 false,这意味着结果始终为 true 或 false; eg:例如:

14 && 0          /// results as 0,  not false
14 || 0          /// results as 14, not true
1 && 2 && 3 && 4 /// results as 4,  not true
true && ''       /// results as ''
{} || '0'        /// results as {}

One main benefit, compared with a normal if statement, is that the first two methods can operate on the righthand-side of an argument ie as part of an assignment.与普通的 if 语句相比,一个主要的好处是前两种方法可以在参数的右侧操作,即作为赋值的一部分。

d = (a && b) || c;
d = a ? b : c;

if `a == true` then `d = b` else `d = c`

The only way to achieve this with a standard if statement would be to duplicate the assigment:使用标准 if 语句实现此目的的唯一方法是复制分配:

if ( a ) { d = b } else { d = c }

You may ask why use just Logical Operators instead of the Ternary Operator , for simple cases you probably wouldn't, unless you wanted to make sure a and b were both true.你可能会问为什么只使用逻辑运算符而不是三元运算符,对于简单的情况你可能不会,除非你想确保ab都是真的。 You can also achieve more streamlined complex conditions with the Logical operators, which can get quite messy using nested ternary operations... then again if you want your code to be easily readable, neither are really that intuative.您还可以使用逻辑运算符实现更简化的复杂条件,使用嵌套的三元运算可能会变得非常混乱......再一次,如果您希望您的代码易于阅读,那么两者都不是那么直观。

In plain English, the syntax explained:用简单的英语,语法解释:

if(condition){
    do_something_if_condition_is_met;
}
else{
    do_something_else_if_condition_is_not_met;
}

Can be written as:可以写成:

condition ? do_something_if_condition_is_met : do_something_else_if_condition_is_not_met;

If you just want an inline IF (without the ELSE), you can use the logical AND operator:如果您只想要一个内联 IF(没有 ELSE),您可以使用逻辑 AND 运算符:

(a < b) && /*your code*/;

If you need an ELSE also, use the ternary operation that the other people suggested.如果您还需要 ELSE,请使用其他人建议的三元运算。

你可以在 JavaScript 中这样做:

a < b ? passed() : failed();
<div id="ABLAHALAHOO">8008</div>
<div id="WABOOLAWADO">1110</div>

parseInt( $( '#ABLAHALAHOO' ).text()) > parseInt( $( '#WABOOLAWADO ).text()) ? alert( 'Eat potato' ) : alert( 'You starve' );

I often need to run more code per condition, by using: ( , , ) multiple code elements can execute:我经常需要在每个条件下运行更多代码,通过使用: ( , , )可以执行多个代码元素:

var a = 2;
var b = 3;
var c = 0;

( a < b ?  ( alert('hi'), a=3, b=2, c=a*b ) : ( alert('by'), a=4, b=10, c=a/b ) );

FYI, you can compose conditional operators仅供参考,您可以编写条件运算符

var a = (truthy) ? 1 : (falsy) ? 2 : 3;

If your logic is sufficiently complex, then you might consider using an IIFE如果您的逻辑足够复杂,那么您可以考虑使用IIFE

var a = (function () {
  if (truthy) return 1;
  else if (falsy) return 2;
  return 3;
})();

Of course, if you plan to use this logic more than once, then you aught to encapsulate it in a function to keep things nice and DRY.当然,如果您打算多次使用此逻辑,那么您应该将其封装在一个函数中以保持良好和干燥。

inline if:内联如果:

(('hypothesis') ? 'truthy conclusion' : 'falsey conclusion')

truthy conclusion: statements executed when hypothesis is true真实结论:假设为真时执行的语句

falsey conclusion: statements executed when hypothesis is false错误结论:假设为假时执行的语句

your example:你的例子:

var c = ((a < b) ? 'a<b statements' : '!(a<b) statements');

To add to this you can also use inline if condition with && and ||要添加到这一点,您还可以使用带有 && 和 || 的内联 if 条件。 operators.运营商。 Like this像这样

var a = 2;
var b = 0;

var c = (a > b || b == 0)? "do something" : "do something else";

Inline if in JavaScript is simple and requires no braces: JavaScript 中的内联if很简单,不需要大括号:

if (a < b) doSomething()

Technically you can have an else in the same line, but it requires a semicolon:从技术上讲,您可以在同一行中有一个else ,但它需要一个分号:

if (a < b) doSomething(); else doSomethingElse()

The above examples may not be desired by your team's coding standards.您的团队的编码标准可能不希望使用上述示例。 The most important thing is that you follow conventions that work for your team.最重要的是您遵循适用于您的团队的约定。 Personally, I prefer if statements over ternaries in many cases because I find them easier to read.就个人而言,在许多情况下,我更喜欢if语句而不是三元语句,因为我发现它们更易于阅读。

Isn't the question essentially: can I write the following?本质上不是问题:我可以写以下内容吗?

if (foo)
  console.log(bar)
else
  console.log(foo + bar)

the answer is, yes, the above will translate.答案是,是的,上面会翻译。

however, be wary of doing the following但是,请注意以下操作

if (foo)
  if (bar)
    console.log(foo)
  else 
    console.log(bar)
else 
  console.log(foobar)

be sure to wrap ambiguous code in braces as the above will throw an exception (and similar permutations will produce undesired behaviour.)确保将模棱两可的代码包含在大括号中,因为上面会引发异常(并且类似的排列会产生不希望的行为。)

Simplify ternary operator简化三元运算符

var locked = 1;
var canChange = locked != 1 ? true : false;

If the locked is 1, then the canChange variable is set to false , otherwise, it is set to true.如果locked 为1,则canChange变量设置为false ,否则设置为true。 In this case, you can simplify it by using a Boolean expression as follows:在这种情况下,您可以使用布尔表达式来简化它,如下所示:

var locked = 1;
var canChange = locked != 1;

For multiple JavaScript ternary operators The following example shows how to use two ternary operators in the same expression:对于多个 JavaScript 三元运算符 以下示例展示了如何在同一个表达式中使用两个三元运算符:

var speed = 90;
var message = speed >= 120 ? 'Too Fast' : (speed >= 80 ? 'Fast' : 'OK');
console.log(message);

It is a best practice to use the ternary operator when it makes the code easier to read.当它使代码更易于阅读时,最好使用三元运算符。 If the logic contains many if...else statements, you shouldn't use the ternary operators.如果逻辑包含许多 if...else 语句,则不应使用三元运算符。

You can use the Ternary operator which equates to a simple if, else.您可以使用三元运算符,它等同于简单的 if 和 else。

Ternary operation which calls functions for both outcomes:为两种结果调用函数的三元运算:

(a < b) ? DoSomething() : DoSomethingElse();

Ternary operation which calls a function for only one of the outcomes:三元运算仅针对其中一个结果调用函数:

(a < b) ? DoSomething() : {}; or (a < b)?.DoSomething();

(condition) ? (健康)状况) ? expressionTrue : expressionFalse;表达式真:表达式假;

Example例子

int a=20, b=10;

if (a>b) {
  cout << "a greater than b";
} else {
  cout << "b greater than a";
} 

You can simply write:你可以简单地写:

int a=20, b=10;

(a>b) ? cout << "a greater than b" : cout << "b greater than a";

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

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