localStorage cheatsheet

YIM_JI·2023년 4월 22일
0

CRD

interface Storage {
    /** 키/벨류 쌍의 갯수 리턴 */
    readonly length: number;
    /**
     * 모든 키/벨류 쌍을 삭제한다.
     */
    clear(): void;
    /** 받은 키가 있으면 키와 관련된 현재 벨류를 리턴, 없으면 null 리턴 */
    getItem(key: string): string | null;
  	/** 받은 인덱스번째 키의 네임을 반환, 인덱스가 키벨류쌍의 길이보다 크거나 같으면 null  */
    key(index: number): string | null;
    /**
     * 받은 키가 존재하면 해당하는 키/벨류 쌍을 삭제.
     */
    removeItem(key: string): void;
    /**
     * 받은 키가 존재하지 않는다면, 받은 키와 벨류를 생성한다.
     */
    setItem(key: string, value: string): void;
    [name: string]: any;
}

JSON.stringify(), JSON.parse()

// 객체를 JSON 포맷의 문자열로 변환하면서 들여쓰기 한다.
const prettyJson = JSON.stringify(obj, null, 2);
const parsed = JSON.parse(prettyJson);

filter

// replacer 함수. 값의 타입이 Number이면 필터링되어 반환되지 않는다.
function filter(key, value) {
  // undefined: 반환하지 않음
  return typeof value === 'number' ? undefined : value;
}

// JSON.stringify 메서드에 두 번째 인수로 replacer 함수를 전달한다.
const strFilteredObject = JSON.stringify(obj, filter, 2);
console.log(typeof strFilteredObject, strFilteredObject);
/*
string {
  "name": "Lee",
  "alive": true,
  "hobby": [
    "traveling",
    "tennis"
  ]
}
*/

0개의 댓글