Recently, I encountered many if statements that could be rewritten as switch statements or && operators. Feel very succinct, so since comprehensive summary.

If statement

 if (ops[i] === "C") {
      res.pop()
    } else 
    if (ops[i] === "D") {
      res.push(res[res.length-1] * 2)}else 
    if (ops[i] === "+") {
      res.push(res[res.length - 1] + res[res.length -2])}else 
    if 
    (parseInt(ops[i]) ! = =NaN) {
      res.push(Math.floor(ops[i]))
    }
Copy the code

The if statement is the most common and most straightforward, but it’s too much code to look very clean. Can be rewritten as:

A switch statement

switch (ops[i]) {
  case "C":
    res.pop()
    break;
  case "D":
    res.push(+res[res.length-1] * 2)
    break;
  case "+":
    res.push(+res[res.length - 1] + +res[res.length -2])
    break;
  default:
    res.push(+ops[i]);
}
Copy the code

The switch statement looks much cleaner, but it can’t be implemented in cases where unequal judgments are required. Therefore, the available situation is relatively small.

&& | | statements

(ops[i] === "C" && res.pop()) || (ops[i] === "D" && res.push(+res[res.length-1] * 2)) || (ops[i] === "+" && res.push(+res[res.length - 1] + +res[res.length -2) | | (parseInt(ops[i]) ! = =NaN && res.push(Math.floor(ops[i]))))
Copy the code

This can be done in a single line of code. && | | statement, also known as a short circuit. That is, if the statement preceded by && is true, the statement is equal to the value following && (true/false). If | | in front of a statement is false, then this statement is | | the value behind the (true/false). My understanding is at the beginning, && is approximately equal to the if (), | | is approximately equal to the else, but && | | operators in with, or is the nature of judgment. If ops[I] === “C” runs true, then it is true && res.pop(), which is res.pop() and is judged true. And followed by the | | operator, surrounded by the current judgment to true won’t back to operation. So the end result is res.pop(). And if the result is false, the ops [I] = = = “C” && res. Pop () the whole is false, then through the back of the | | operators continue to back operations, to look behind. So this gives people a kind of if… Else statement illusion. In fact, these two ways, only the final result is the same, but the operation principle is different. && | | operators wording, although very simple, refined. But the logic involved is very complicated. It’s not usually used for a lot of development. Poor maintainability. The following is an exception:

var YAHOO = window.YAHOO || {};
Copy the code

or

this.name = name || 'mama';
Copy the code