✏️1주차 QUIZ

박시은·2023년 5월 28일
0

JavaScript

목록 보기
17/58
post-thumbnail

▶ Quiz 1. 안녕 JS!

제출할 디렉토리 이름ex00
제출할 파일 이름hello.js

실행 시 Hello JS! 를 콘솔에 출력하는 프로그램을 작성하세요.


▷ 풀이

  1. 디렉토리 생성하여 코드 관리

  1. Hello JS! 를 콘솔에 출력
console.log("Hello JS!");

  1. 파일 실행 결과



▶ Quiz 2. 자료형 타입 맞추기

제출할 디렉토리 이름ex01
제출할 파일 이름helloSomeone.js

실행 시 매개변수를 가져와 인사를 출력하는 함수 helloSomeone을 작성하세요. 매개변수로는 문자열, 숫자, NaN, undefined, null이 들어올 수 있으며, 어떤 매개변수냐에 따라 다음과 같은 동작을 하는 함수를 구현해야 합니다.

  • 매개변수로 문자열이 들어온 경우, "Hello 문자열!" 을 출력해야합니다. 만약 문자열이 빈 문자열이라면 "Who are you?" 를 출력합니다.
  • 매개변수로 null 이 들어온 경우, "I am null and void" 를 출력해야합니다.
  • 매개변수로 숫자가 들어온 경우, "My age is 숫자" 를 출력해야합니다. 단, 숫자가 음수나 0 의 경우 "I am Benjamin Button!" 을 출력합니다.
  • 매개변수로 NaN가 들어온 경우, "Age is just a number" 를 출력해야합니다.
  • 매개변수로 undefined가 들어온 경우 "Nobody can define me!" 를 출력해야합니다.
function helloSomeone(value) {
	//이곳에 조건문 작성하여 data 검사
}

helloSomeone("42");
helloSomeone("");
helloSomeone(null);
helloSomeone(42);
helloSomeone(-1);
helloSomeone(NaN);
helloSomeone(undefined);

💡hint!
자바스크립트 typeof 연산자로 변수타입 확인하기


▷ 풀이

typeof 연산자는 다음과 같은 자료형을 검사할 수 있다.
undefined boolean number string bigint symbol function object (null을 포함한 모든 객체)


주의해야할 자료형

  • ⚠️ typeof null은 'null'이 아닌 'object'를 반환!!
    이는 자바스크립트의 설계 상 문제로(오류), null이 객체가 아닌 원시 값이기 때문
    따라서, value === null처럼 직접 null과 비교해야 한다.

  • ⚠️ NaN은 number을 반환하므로 NaN 값을 체크하려면 Number.isNaN 함수를 사용해야한다.
    Number.isNaN() 함수는 인수가 NaN과 동일하면 true, 그렇지 않으면 false를 반환

  • ⚠️ boolean 에서 flase 를 나타내는 값: 0, null, undefined, NaN, ''(공백문자)
    true는 false를 제외한 나머지 전부 다

function helloSomeone(value) {
  //이곳에 조건문 작성하여 data 검사

  //매개변수: 문자열
  if (typeof value === "string") {
    if (value === "") {
      console.log("Who are you?");
    } else {
      console.log("Hello " + value);
    }
  }

  // 매개변수: 숫자
  else if (typeof value === "number") {
    if (value < 0 || value == 0) {
      console.log("I am Benjamin Button");
    }
    if (typeof value === "number" && typeof value === "!NaN") {
      console.log("My age is " + value);
    }
  }

  // 매개변수: null
  else if (value === null) {
    console.log("I am null and void");
  }

  //매개변수: NaN
  else if (Number.isNaN(value)) {
    console.log("Age is just a number");
  }

  //매개변수: undefined
  else if (typeof value === "undefined") {
    console.log("Nobody can define me!");
  }
}
helloSomeone("22");
helloSomeone("");
helloSomeone(null);
helloSomeone(22);
helloSomeone(-1);
helloSomeone(NaN);
helloSomeone(undefined);

profile
블로그 이전했습니다!

0개의 댓글