[JavaScript] 빈 값 체크하기(null, undefined, "", [], {})

seunghwan·2022년 8월 24일
2

JavaScript

목록 보기
7/7
post-thumbnail

빈 값 체크 메서드 구현 👀


isEmpty 메서드

  • 입력값이 다음과 같을 경우,
    빈 값이라고 판단, true를 반환한다.

    • undefined 타입
    • null 값
    • 빈 문자열
    • 문자열 null
    • 빈 배열
    • 빈 객체
  • Object.keys(obj) 👈🏻 객체의 key값들을 모아 String 배열로 반환해준다


테스트

  • 테스트
  • 입력값에 따라 결과가 잘 나온다✔

코드

// 빈 값 체크 함수
const isEmpty = (input) => {
    if (
         typeof input === "undefined" ||
         input === null ||
         input === "" ||
         input === "null" ||
         input.length === 0 ||
         (typeof input === "object" && !Object.keys(input).length)
        )
    {
        return true;
    }
    else return false;
}

// test
console.log("입력값 없음 결과 :",isEmpty());
console.log("undefined 결과 :",isEmpty(undefined));
console.log("null 결과 :",isEmpty(null));
console.log("빈 문자열 결과 :",isEmpty(""));
console.log("null 문자열 결과 :",isEmpty("null"));
console.log("빈 배열 결과 :",isEmpty([]));
console.log("빈 객체 결과 :",isEmpty({}));
profile
소소한 개발일지💻

0개의 댓글