Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - 您如何使用? :(条件)运算符在JavaScript中?(How do you use the ? : (conditional) operator in JavaScript?)

有人可以简单地向我解释什么是?:有条件的“三元”)运算符,以及如何使用它?

  ask by muudless translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a one-line shorthand for an if-else statement.(这是if-else语句的单行简写。)

It's called the conditional operator.(它称为条件运算符。) 1(1个) Here is an example of code that could be shortened with the conditional operator:(这是可以通过条件运算符缩短的代码示例:) var userType; if (userIsYoungerThan18) { userType = "Minor"; } else { userType = "Adult"; } if (userIsYoungerThan21) { serveDrink("Grape Juice"); } else { serveDrink("Wine"); } This can be shortened with the ?: like so:(可以使用?:来缩短它,就像这样:) var userType = userIsYoungerThan18 ? "Minor" : "Adult"; serveDrink(userIsYoungerThan21 ? "Grape Juice" : "Wine"); Like all expressions, the conditional operator can also be used as a standalone statement with side-effects, though this is unusual outside of minification:(与所有表达式一样,条件运算符也可以用作具有副作用的独立语句,尽管在缩小之外这是不常见的:) userIsYoungerThan21 ? serveGrapeJuice() : serveWine(); They can even be chained:(它们甚至可以链接:) serveDrink(userIsYoungerThan4 ? 'Milk' : userIsYoungerThan21 ? 'Grape Juice' : 'Wine'); Be careful, though, or you will end up with convoluted code like this:(但是要小心,否则最终将得到如下复杂的代码:) var k = a ? (b ? (c ? d : e) : (d ? e : f)) : f ? (g ? h : i) : j; 1 Often called "the ternary operator," but in fact it's just a ternary operator [an operator accepting three operands].(1 通常称为“三元运算符”,但实际上它只是一个三元运算符[一个接受三个操作数的运算符]。) It's the only one JavaScript currently has, though.(不过,这是目前唯一的JavaScript。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...