开发者

How to write an IF else statement without 'else' in JavaScript [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.

This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.

Closed 2 years ago.

Improve this question

I can't use else in my script; how can I implement an if else statement without using else?

I'm trying to resize a div:

function hideTable(开发者_高级运维){
    var table = document.getElementById('PDemo');
    if(table.style.width == "50%") table.style.width = "150px";
    if(table.style.width == "150px") table.style.width = "50%";
}

This script doesn't work because as soon as the first if statement is executed, the condition for the second if statement becomes true, so that executes too, and thus nothing changes.


The ternary operator:

condition ? execTrue() : execFalse();

This is equivalent to:

if (condition) {
    execTrue();
}
else {
    execFalse();
}

You can write an if/else in 1 line, just don't press enter...

if (condition) { execTrue(); } else { execFalse(); }

Further, you can write any statement of arbitrary complexity on one line:

if(condition1) { exec1(); } else if(condition2) { exec2(); } else { execFalse() }

If you're having the issue where the second if statement executes as well, you want to impose mutual exclusion, i.e., using else if instead of just if on each subsequent conditional.


Save the value into a different variable.

function hideTable(){
  var table = document.getElementById('PDemo');
  var width = table.style.width;
  if(width == "50%") table.style.width = "150px";
  if(width == "150px") table.style.width = "50%";
}


If you can't use an else (and that is crazy), use a switch.

switch (table.style.width) {

    case '50%':
       ...
       break;

    case '150px':
       ...
       break;

}


if(/*condition a*/){/*statements a*/}else if(/*condition b*/){/*statements b*/}else{/*statements c/*}

One line only.


With a while loop for the sake of uniqueness.

while (!resized){
  if(width == "50%") {table.style.width = "150px";resized=true;break};
  if(width == "150px") table.style.width = "50%";resized=true;break};
  resized=true;
}


The && operator is called a short-circuit operator. It will return the value of the second operand based on the value of the first operand.

For example: (explanation : If 'profile' permission exists in permArray then load the user's profile)

isPermitted(permArray, 'profile') && loadProfile();

The && operator is useful also for checking for null objects before accessing their attributes. For example...

var name = person && person.getName();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜