자바스크립트 - 조건문

돌고돌아아아·2021년 7월 13일
0

꼬 자바스크립트

목록 보기
7/8

특정 조건에 따라 작업을 수행한다.

if... else 문

한가지 조건으로 두 가지 결과를 갖고 오고자 할 때

기본구조
if(조건) {
	조건에 부합할 때 코드를 실행
} else {
	조건과 다른 그외의 상황에서 코드를 실행
}
이 구조 또한 위의 코드와 똑같이 실행된다.
if (조건) {
	조건에 부합할 때 코드를 실행
}
다른 코드를 실행  // 항상 실행되는 것에 주의해야함
예시	
let shoppingDone = false;
let childsAllowance;
if (shoppingDone === true) {
  childsAllowance = 10;
} else {
  childsAllowance = 5;
}
//  5를 반환

if... else if 문

두개 이상의 조건으로 여러 결과를 갖고 오고자 할 때

예시

<label for="weather">Select the weather type today: </label>
<select id="weather">
  <option value="">--Make a choice--</option>
  <option value="sunny">Sunny</option>
  <option value="rainy">Rainy</option>
  <option value="snowing">Snowing</option>
  <option value="overcast">Overcast</option>
</select>

<p></p>
const select = document.querySelector('select');
const para = document.querySelector('p');

select.addEventListener('change', setWeather);

function setWeather() {
  const choice = select.value;

  if (choice === 'sunny') {
    para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
  } else if (choice === 'rainy') {
    para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.';
  } else if (choice === 'snowing') {
    para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
  } else if (choice === 'overcast') {
    para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
  } else {
    para.textContent = '';
  }
}

조건문에서의 비교 연산자 참고

조건을 테스트할 때 사용

=== 또는 !== : 왼쪽의 값이 오른쪽의 값과 동일하거나 동일하지 않은지 테스트한다.
< 또는 > : 왼쪽의 값이 오른쪽의 값보다 작거나 큰지 테스트한다.
<= 또는 >= : 왼쪽의 값이 오른쪽의 값보다 작거나 같거나 크거나 같은지 테스트한다.

변수자체가 조건부가 될수 있음 (존재, 정의된 것)

예시
let cheese = 'Cheddar';
if (cheese) {
  console.log('Yay! Cheese available for making cheese on toast.');
} else {
  console.log('No cheese on toast for you today.');
} // 존재하기 때문에 if의 코드를 반환함
예시2
let shoppingDone = false;
let childsAllowance;
if (shoppingDone) { // don't need to explicitly specify '=== true'
  childsAllowance = 10;
} else {
  childsAllowance = 5;
}

중첩 if... else

if문 안에 if문

if (choice === 'sunny') {
if (temperature < 86) {
para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
} else if (temperature >= 86) {
para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some sunscreen on.';
}
}

논리연산자 and, or, not

  && : 두 개 이상의 표현식을 연결한다. 두 표현식에 대한 연산자가 모두 해당되어야함
  if (choice === 'sunny' && temperature < 86) {
  para.textContent = 'It is ' + temperature + ' degrees outside — nice and sunny. Let\'s go out to the beach, or the park, and get an ice cream.';
} else if (choice === 'sunny' && temperature >= 86) {
  para.textContent = 'It is ' + temperature + ' degrees outside — REALLY HOT! If you want to go outside, make sure to put some sunscreen on.';
}
  || : 두 개 이상의 표현식을 연결한다. 하나 이상의 표현식이 해당되면 된다.
  if (iceCreamVanOutside || houseStatus === 'on fire') {
  console.log('You should leave the house quickly.');
} else {
  console.log('Probably should just stay in then.');
}
! : not 표현식을 부정하는 데 사용한다.
if (!(iceCreamVanOutside || houseStatus === 'on fire')) {
  console.log('Probably should just stay in then.');
} else {
  console.log('You should leave the house quickly.');
}
논리 연산자를 결합
if ((x === 5 || y > 3 || z <= 10) && (loggedIn || userName === 'Steve')) {
  // run the code
}

switch 문

if... else 문의 단점을 보완해주는 친구
실행할 코드가 긴 경우
조건이 복잡한 경우에 사용하기 좋다.

기본구조

switch (expression) {
    case choice1:
      run this code
      break;
    case choice2:
      run this code instead
      break;
    // include as many cases as you like
    default:	// 선택지에 없을 경우
      actually, just run this code
}

예시

    <label for="weather">Select the weather type today: </label>
    <select id="weather">
      <option value="">--Make a choice--</option>
      <option value="sunny">Sunny</option>
      <option value="rainy">Rainy</option>
      <option value="snowing">Snowing</option>
      <option value="overcast">Overcast</option>
    </select>

    <p></p>
    select.addEventListener('change', setWeather);

    function setWeather() {
      const choice = select.value;

      switch (choice) {
        case 'sunny':
          para.textContent = 'It is nice and sunny outside today. Wear shorts! Go to the beach, or the park, and get an ice cream.';
          break;
        case 'rainy':
          para.textContent = 'Rain is falling outside; take a rain coat and an umbrella, and don\'t stay out for too long.';
          break;
        case 'snowing':
          para.textContent = 'The snow is coming down — it is freezing! Best to stay in with a cup of hot chocolate, or go build a snowman.';
          break;
        case 'overcast':
          para.textContent = 'It isn\'t raining, but the sky is grey and gloomy; it could turn any minute, so take a rain coat just in case.';
          break;
        default:
          para.textContent = '';
      }
    }

삼항 연산자

if...else 문이 true/false 조건이 되는 경우 유용하게 사용된다.

기본구조

조건 ? 참일 때 실행 : 거짓일 때 실행;

( condition ) ? run this code : run this code instead

예시

let greeting = ( isBirthday ) ? 'Happy birthday Mrs. Smith — we hope you have a great day!' : 'Good morning Mrs. Smith.';

삼항 연산자는 변수값을 설정하는 것 뿐만아니라
함수나 코드 등 원하는 모든 것을 실행할 수 있다.
인자 값을 넣어 함수를 실행시킬 수 있음

<label for="theme">Select theme: </label>
<select id="theme">
  <option value="white">White</option>
  <option value="black">Black</option>
</select>

<h1>This is my website</h1>
const select = document.querySelector('select');
const html = document.querySelector('html');
document.body.style.padding = '10px';
function update(bgColor, textColor) {
  html.style.backgroundColor = bgColor;
  html.style.color = textColor;
}
select.onchange = function() {
  ( select.value === 'black' ) ? update('black','white') : update('white','black');
}
profile
민트초코

0개의 댓글

관련 채용 정보