如何在 JavaScript 中编写内联 IF 语句? [英] How to write an inline IF statement in JavaScript?

查看:25
本文介绍了如何在 JavaScript 中编写内联 IF 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 JavaScript 中使用内联 if 语句?是否也有内联 else 语句?

How can I use an inline if statement in JavaScript? Is there an inline else statement too?

像这样:

var a = 2;
var b = 3;

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

推荐答案

您不一定需要 jQuery.仅 JavaScript 就可以做到这一点.

You don't necessarily need jQuery. JavaScript alone will do this.

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

如果值为 truec 变量将为 minor,如果值为 major代码>假.

The c variable will be minor if the value is true, and major if the value is false.

这称为条件(三元)运算符.

This is known as a Conditional (ternary) Operator.

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

这篇关于如何在 JavaScript 中编写内联 IF 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆