관리 메뉴

Silver Library (Archived)

JS - switch 본문

F2. Problem & Solving/Solving

JS - switch

Ayin Kim 2021. 7. 6. 13:39
반응형

Why I use this?

- To group up (or wrap up) a number of string characters to print out a singularly indicated result.

 

Personal note:

So this switch belongs to prototype.

 

Hint:

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

 

Bit more:

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using the strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.)

 

★See the description section from the link below.

 

For example, if I wish to let 'aeiou' to print letter 'A' once it is called or return:

function getLetter(s) {
    let letter;
    // Write your code here
    switch (true) {
        case 'aeiou'.includes(s[0]):
            letter = 'A';
            break;
        case 'bcdfg'.includes(s[0]):
            letter = 'B';
            break;
        case 'hjklm'.includes(s[0]):
            letter = 'C';
            break;
        case 'npqrstvwxyz'.includes(s[0]):
            letter = 'D';
            break;
    }
    return letter;
}

OR probably this would be a better example:

switch (expr) {
  case 'Oranges':
    console.log('Oranges are $0.59 a pound.');
    break;
  case 'Apples':
    console.log('Apples are $0.32 a pound.');
    break;
  case 'Bananas':
    console.log('Bananas are $0.48 a pound.');
    break;
  case 'Cherries':
    console.log('Cherries are $3.00 a pound.');
    break;
  case 'Mangoes':
  case 'Papayas':
    console.log('Mangoes and papayas are $2.79 a pound.');
    break;
  default:
    console.log('Sorry, we are out of ' + expr + '.');
}

console.log("Is there anything else you'd like?");
 

switch - JavaScript | MDN

The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.

developer.mozilla.org

 

'F2. Problem & Solving > Solving' 카테고리의 다른 글

For in, For of 용도  (0) 2021.09.22
JS - wrapper object  (0) 2021.07.07
[Node.js] - what is readline() modul?  (0) 2021.07.06
[JS] string includes() method  (0) 2021.07.06
Loops - JS algorithm  (0) 2021.06.12