logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [JavaScript] JS로 크롬 만들기 2.2. 함수와 조건문

    이미지 보기

    [JavaScript] JS로 크롬 만들기 2.2. 함수와 조건문

    • 22.03.02 작성

    • 읽는 데 3

    TOC

    함수

    prompt()

    • 브라우저에서 사용자에게 입력을 받을 수 있도록 하는 함수
    • message와 default로 구성
    • alert()처럼 브라우저에서 사용하는 함수
    const age = prompt("how old are you?");
    

    특징 : 잘 사용하지는 않는다!

    1. 자바스크립트를 일시 정지시키기 때문
    2. 스타일을 적용할 수 없기 때문
    3. 일부 브라우저는 팝업을 제한하기도 하기 때문

    typeof ??

    ??의 자료형을 볼 수 있게 한다.

    console.log(typeof age);
    

    parseInt()

    string을 number로 형 변환시켜준다.

    console.log(typeof parseInt("121212");)
    console.log(typeof parseInt("hello");)
    
    // number
    // NaN
    

    만약 number로 형을 변환할 수 없는 인자라면 NaN(Not a Number) 표시


    조건문

    isNan()

    무언가가 NaN인지 확인하는 함수 isNaN()을 사용해보자.

    const age = parseInt(prompt("How old are you?"));
    
    console.log(isNan(age));
    

    age가 number이면 true, 아니면 false


    조건문 1 : if - else

    어떠한 조건이 true일 때와 false일 때로 이분해서 코드 실행

    if (isNaN(age)) {
      // condition === true
      console.log("Please write a number");
    } else {
      // condition === false
      console.log("Thank you for writing your age.");
    }
    

    조건문 2 : if - else if - else

    조건이 3가지 이상 필요한 경우 else if 사용

    • && : and
    • || : or
    if (isNaN(age)) {
      // age is not number
      console.log("Please write a number");
    } else if (age < 18) {
      // age is number and age is 18 미만
      console.log("You are too young");
    } else if (age >= 18 && age <= 50) {
      // age is number and age is 18 이상 and under 이하
      console.log("You can drink");
    } else if (age > 50 && age <= 80) {
      // age is number and age is 51 이상 and under 이하
      console.log("You should exercise");
    } else {
      // age is number and age is 81 이상
      console.log("You can do whatever you want");
    }
    
    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다