简体   繁体   中英

How to change a ternary operator into an if-else statement?

How do I change this shorthand ternary operator into an if-else statement?

header.style.width = header.style.width === "1265px" ? '0px' : '1265px';

Conditional (ternary) operator

Syntax

condition? exprIfTrue: exprIfFalse

Parameters

condition
An expression whose value is used as a condition.
exprIfFalse
An expression which is evaluated if the condition evaluates to a truthy value (one which equals or can be converted to true ).
exprIfFalse
An expression which is executed if the condition is falsy (that is, has a value which can be converted to false ).

To translate the above syntax into an if...else statement:

if(condition)
    exprIfTrue
else
    exprIfFalse

In your specific code:

header.style.width = header.style.width === "1265px" ? '0px' : '1265px';

You will have the following equivalent if...else statement:

if(header.style.width === "1265px")
    header.style.width = '0px';
else
    header.style.width = '1265px';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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