(11장) 자바스크립트 표준 라이브러리[자바스크립트 완벽 가이드 7판]

iberis2·2023년 2월 20일
0

자바스크립트 표준 라이브러리, API

목차
1. Set과 Map
2. 형식화 배열
3. 정규표현식
4. Date 클래스
5. Error 클래스
6. JSON 직렬화와 역직렬화
7. 국제화(Intl) API
8. console API
9. URL API
10. 타이머


1. Set 과 Map

Set 클래스는 중복되지 않는 값으로만 이루어진 컬렉션이다.

  • 인덱스와 순서가 없다
    • 하지만 요소이 삽입 순서를 기억하며, 순회할 때 삽입 순서대로 순회한다
  • 중복을 허용하지 않는다
  • 이터러블이며, for/of 루프로 열거 가능하고, forEach() 메서드를 지원한다.
    • 인덱스가 없으므로 forEach()는 첫 번째와 두 번째 인자 모두 요소 값을 전달한다.

Map 클래스는 키로 구성된 값의 집합이며 각 키는 다시 다른 값과 연결된다.

  • 자바스크립트 값이라면 어떤 것이든 맵의 키나 값으로 사용할 수 있다.
  • 요소의 삽입 순서를 기억한다.
  • 이터러블이며 keys(), values(), entries(), forEach() 메서드를 사용할 수 있다.
    • forEach()의 첫 번째 인자는 맵의 값이고, 두 번째 인자는 맵의 키를 전달한다.

WeakMap과 WeakSet

  • WeakMap의 키는 반드시 객체 또는 배열이어야 한다.
    • 기본 값은 키로 사용할 수 없다.
  • WeakMap에는 get(), set(), has(), delete() 메서드만 있다.
    • keys(), values(), forEach() 메서드와 size 프로퍼티가 없다.
  • WeakSet은 요소로 기본값을 사용할 수 없다.
  • WeakSet은 add(), has(), delete() 메서드만 가지고, 이터러블이 아니다.
    • size 프로퍼티도 없다.

2. 형식화 배열(typed array)

  • Array.isArray() 는 false이다.
  • 요소가 모두 숫자이다.
    • 저장하는 숫자 타입(부호 있는/없는 정수, IEEE-754 부동 소수점 숫자)과 크기(8비트 ~ 64비트)를 지정할 수 있다.
  • 생성할 때 길이를 정하고, 바꿀 수 없다.
    • 요소는 항상 0으로 초기화된다.

3. 정규 표현식과 패턴 매칭

정규 표현식은 텍스트 패턴을 정의하는 객체이다. 자바스크립트에서는 RegExp 객체로 표현한다.
드림코딩 정규표현식 정리 깃허브
정규표현식 연습용 사이트

Groups and ranges

Character
\|또는
()그룹
[]문자셋, 괄호안의 어떤 문자든
[^]부정 문자셋, 괄호안의 어떤 문가 아닐때
(?:)찾지만 기억하지는 않음

Quantifiers

Character
?없거나 있거나 (zero or one)
*없거나 있거나 많거나 (zero or more)
+하나 또는 많이 (one or more)
{n}n번 반복
{min,}최소
{min,max}최소, 그리고 최대

Boundary-type

Character
\b단어 경계
\B단어 경계가 아님
^문장의 시작
$문장의 끝

Character classes

Character
\특수 문자가 아닌 문자
.어떤 글자 (줄바꿈 문자 제외)
\ddigit 숫자
\Ddigit 숫자 아님
\wword 문자
\Wword 문자 아님
\sspace 공백
\Sspace 공백 아님

4. 날짜와 시간 Date() 객체

[참고] 어느 지역 기준으로 시간대가 설정되어 있는지 확인하는 코드

let 기준지역 = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(기준지역); // Asia/Seoul

🗓 문자형 날짜 → Date 객체로 변환

let date1 = "2023-02-06";
let date2 = "2023-02-07";
let date3 = "2023.02.08";

let date2Ary = date2.split("-"); // ['2023', '02', '07']
let date3Ary = date3.split("."); // ['2023', '02', '08']

date1 = new Date(date1);
date2 = new Date(date2Ary[0], date2Ary[1] - 1, date2Ary[2]);
date3 = new Date(date3Ary[0], date3Ary[1] - 1, date3Ary[2]);

console.log(date1.toLocaleString()); // 2/6/2023, 9:00:00 AM
console.log(date2.toLocaleString()); // 2/7/2023, 12:00:00 AM
console.log(date3.toLocaleString()); // 2/8/2023, 12:00:00 AM

new Date() : 년, 월은 필수, 나머지는 옵션

  • 아규먼트를 전달하지 않으면 현재 날짜와 시간 인스턴스 객체를 반환한다.
  • 숫자 타입을 전달하면 1970년 1월 1일 00:00(UTC)을 기점으로 밀리초만큼 경과한 날짜와 시간 인스턴스 객체를 반환한다.
  • 2개 이상의 숫자 타입을 전달하면 연, 월, 일, 시, 분, 초, 밀리초 인스턴스 객체를 반환한다.
    • 단, 월이 0(= 1월) ~ 11(=12월)로 표현되므로 -1을 해줘야 한다.
  • 문자열을 전달하면 지정된 날짜와 시간 인스턴스 객체를 반환한다.
    • 단, 문자열이 Date.parse 메소드에 의해 해석 가능한 형식이어야 한다.
    let date4 = new Date("12/15/1999 05:25:30");
    let date5 = new Date("December 15, 1999 05:25:30");
    let date6 = new Date("Dec 15 1999 05:25:30");
  • new 없이 호출할 경우 문자열을 반환한다.
    • Date.prototype 메서드를 사용할 수 없다.
    let date7 = Date();
    console.log(typeof date7); // string
    console.log(date7); // Tue Feb 07 2023 21:56:57 GMT+0900 (Korean Standard Time)
    date7.getDay(); // TypeError: date4.getDay is not a function

🗓 년(year) 더하고 빼기

/* 1년 더하기 */
date1.setFullYear(date1.getFullYear() + 1);
console.log(date1.toLocaleString()); // 2/6/2024, 9:00:00 AM

/* 1년 빼기 */
date2.setFullYear(date2.getFullYear() - 1);
console.log(date2.toLocaleString()); // 2/7/2022, 12:00:00 AM

getFullYear() 년도를 나타내는 4자리 숫자를 반환/설정한다.
setFullYear() 년도는 필수 옵션으로 월, 일도 설정 가능하다.

🗓 월(month) 더하고 빼기

/* 1개월 더하기 */
date1.setMonth(date1.getMonth() + 1);
console.log(date1.toLocaleString()); // 3/6/2024, 9:00:00 AM

/* 1개월 빼기 */
date2.setMonth(date2.getMonth() - 1);
console.log(date2.toLocaleString()); // 1/7/2022, 12:00:00 AM

getMonth() 월을 나타내는 0 ~ 11의 정수를 반환/설정한다.
setMonth() 월은 필수 옵션으로 일도 설정 가능하다.

🗓 일(day) 더하고 빼기

/* 1일 더하기 */
date1.setDate(date1.getDate() + 1);
console.log(date1.toLocaleString()); // 3/7/2024, 9:00:00 AM

/* 1일 빼기 */
date2.setDate(date2.getDate() - 1);
console.log(date2.toLocaleString()); // 1/6/2022, 12:00:00 AM

getDate() setDate() 날짜(1 ~ 31)를 나타내는 정수를 반환/설정한다.

요일일요일월요일화요일수요일목요일금요일토요일
반환값0123456

getDay() 요일(0 ~ 6)를 나타내는 정수를 반환한다.

  • setDay 는 없다.

📆 월의 마지막 날짜 찾기

let lastDay = new Date(2024, 2, 0);
console.log(lastDay.toLocaleString()); // 2/29/2024, 12:00:00 AM

음수(-1, -2 ...)를 입력하면 전 달의 마지막날의 1일 전, 2일 전... 을 확인할 수 있다.

📆 31일이 넘어가는 월 계산

월마다 일 수(28일, 30일, 31일)가 다르므로 setMonth()로 +/- 계산을 할 때, 예상하지 못한 결과가 나올 수 있다. \
이를 방지하기 위해 각 달의 말일과 1일을 계산하는 함수로 정확한 n달 전(또는 후)를 리턴하는 함수를 만들어 사용할 수도 있다.

function addMonth(date, month) {
  // month달 후의 1일
  let addMonthFirstDate = new Date(
    date.getFullYear(),
    date.getMonth() + month,
    1
  );

  // month달 후의 말일
  let addMonthLastDate = new Date(
    addMonthFirstDate.getFullYear(),
    addMonthFirstDate.getMonth() + 1,
    0
  );

  // 계산한 달의 마지막 날짜가 기준 날짜보다 작으면 그 달의 마지막 날짜 반환
  let result = addMonthFirstDate;
  if (date.getDate() > addMonthLastDate.getDate()) {
    result.setDate(addMonthLastDate.getDate());
  } else {
    result.setDate(date.getDate());
  }
  return result;
}

// 3월 31일의 11개월 후
let date1 = new Date("2023-03-31");
let monthLater = addMonth(date1, 11);
console.log(monthLater.toLocaleString()); // 2/29/2024, 12:00:00 AM

타임스태프

let startTime = Date.now();
시간이_걸리는_작업_함수();
let endTime = Date.now();
console.log(`${endTime} - ${startTime}ms 이 소요됩니다.`)

Date.now() 메서드로 코드 실행 시간을 확인할 수도 있다.
날짜와 마찬가지로 시간에도 getTime(), setTime() 메서드가 있다.
performance.now() 메서드는 Date.now()보다 정밀한 시간을 측정할 때 사용할 수 있다.

  • node.js에서 사용하려면 const {performance} = require("perf_hooks"); 로 가져온 후 사용할 수 있다.

5. Error 클래스

프로퍼티와 메서드

try {
  throw new Error("새로운 에러");
} catch (error) {
  console.log(`message 프로퍼티: ${error.message}`);
  console.log(`name 프로퍼티: ${error.name}`);
  console.log(`toString 메서드: ${error.toString()}`);
  console.log(`---구분선---`);
  console.log(`stack 프로퍼티: ${error.stack}`);
  console.log(`---구분선---`);
}

/* message 프로퍼티: 새로운 에러
name 프로퍼티: Error
toString 메서드: Error: 새로운 에러 
---구분선---
stack 프로퍼티: Error: 새로운 에러
    at Object.<anonymous> (/Users/snow/Desktop/Study/JavaScript 스터디/11장 표준라이브러리.js:2:9)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47
---구분선---
*/

message 프로퍼티 값은 Error() 생성자에 전달한 값이다.
name 프로퍼티 값은 항상 Error 이다.
toString() 메서드 값은 name프로퍼티 값: message 프로퍼티 값 이다.
stack프로퍼티 값은 Error 객체가 생성된 순간의 콜스택을 담은 스택 추적이다.
예상하지 못한 에러를 캐치했을 때 로그를 남기기 편리하다.

6. JSON 직렬화와 분석

stringify 직렬화

자바스크립트 객체와 배열 리터럴 문법을 사용해 객체와 배열을 포함한 데이터 구조를 문자열로 변환한다.

const rabbit = {
  name: "tori",
  age: 2,
  중성화: true,
  size: null,
  birthDate: new Date(),
  symbol: Symbol("id"),
  jump: () => {
    console.log(`${name} can jump!`);
  },
};

/* Symbol, jump 함수는 직렬화되지 않는다. */
let json = JSON.stringify(rabbit);
console.log(json);
// {"name":"tori","age":2,"중성화":true,"size":null,"birthDate":"2023-02-19T12:07:30.409Z"}

/* 두 번쨰 인자로 배열 또는 콜백 함수를 전달하면 원하는 프로퍼티만 직렬화할 수 있다.
콜백 함수의 첫 번째 인자는 프로퍼티 네임(또는 배열의 인덱스)이고,
두 번째 인자는 프로퍼티 값이다. */
json = JSON.stringify(rabbit, ["name", "age"]);
console.log(json); // {"name":"tori","age":2}

json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return value;
});
console.log(value);
// TypeError: Cannot convert a Symbol value to a string
// Symbol은 TypeError가 발생하므로 지우거나 주석 처리해야한다.
/* 
key: , value: [object Object]
key: name, value: tori
key: age, value: 2
key: 중성화, value: true
key: size, value: null
key: birthDate, value: 2023-02-19T13:04:57.121Z
key: jump, value: () => {
    console.log(`${this.name} can jump!`);
  }
{"name":"tori","age":2,"중성화":true,"size":null,"birthDate":"2023-02-19T13:04:57.121Z"}
*/
JSON 지원여부데이터 형식
지원함숫자, 문자열, boolean 값, null, 배열, 객체
지원 안함Map, Set, Symbol, 정규표현식, Date, 형식화 배열, 함수
// 3번째 인자를 전달하면 데이터를 여러행 형식으로 변환한다.
let obj = { str: "test", num: 0 };

let s1 = JSON.stringify(obj);
console.log(s1); // {"str":"test","num":0}

// `\n`과 같은 공백 문자열이면 들여 쓸 때마다 해당 문자를 사용한다.
let s2 = JSON.stringify(obj, null, "\n");
console.log(s2);
/* {

"str": "test",

"num": 0
}
 */

// 숫자이면 들여 쓸 때마다 그 수만큼 스페이스를 써서 들여쓴다.
let s3 = JSON.stringify(obj, null, 2);
console.log(s3);
/* {
  "str": "test",
  "num": 0
}*/

let r = JSON.parse(s3);
console.log(r); // { str: 'test', num: 0 }

JSON.stringify()에 선택 사항인 세번째 인자를 전달하면 데이터를 여러 행 형식으로 변환한다.
JSON.parse()는 공백을 무시하므로 여러 행의 문자열을 데이터 구조로 변환할 때에는 아무 영향을 주지 않는다.

parse 역직렬화

const rabbit = {
  name: "tori",
  age: 2,
  중성화: true,
  size: null,
  birthDate: new Date(),
  symbol: Symbol("id"),
  jump: function () {
    console.log(`${this.name} can jump!`);
  },
};

let json = JSON.stringify(rabbit);

let obj = JSON.parse(json);
console.log(obj);
/* {
  name: 'tori',
  age: 2,
  '중성화': true,
  size: null,
  birthDate: '2023-02-19T14:21:52.880Z'
} */

// 메서드는 직렬화되지 않았으므로 역직렬화할 수 없다.
rabbit.jump(); // tori can jump!
obj.jump(); // TypeError: obj.jump is not a function

// Date 객체는 자동으로 문자열로 직렬화되었다.
console.log(rabbit.birthDate.getDate()); // 19
console.log(obj.birthDate.getDate());
// TypeError: obj.birthDate.getDate is not a function

/* 두 번째 인자로 콜백함수를 전달할 수 있다 
콜백 함수의 첫 번째 인자는 프로퍼티 네임(또는 배열의 인덱스)이고,
두 번째 인자는 프로퍼티 값이다. */
obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  return key === "birthDate" ? new Date(value) : value;
});

/* key: name, value: tori
key: age, value: 2
key: 중성화, value: true
key: size, value: null
key: birthDate, value: 2023-02-19T14:31:04.771Z
key: , value: [object Object]
 */

console.log(obj.birthDate.getDate()); // 19

rabbit 객체의 메서드 jump 함수는 직렬화되지 않았으므로, 역직렬화 한 obj 객체에는 jump 메서드가 없다.
Date 객체는 직렬화하면 자동으로 문자열로 변환된다. 이를 역직렬화하면 문자열로 반환되므로 Date 객체의 메서드를 사용할 수 없다.
두 번째 인자콜백함수를 전달해, Date 객체로 변환시키면 메서드를 사용할 수 있다.

깊은 복사

const deepCopy = (obj) => JSON.parse(JSON.stringify(obj));

const obj = [1, 2, [3, 4, [5]]];

const copyObj = deepCopy(obj);
copyObj.push(6);

console.log(obj); // [ 1, 2, [ 3, 4, [ 5 ] ] ]
console.log(copyObj); // [ 1, 2, [ 3, 4, [ 5 ] ], 6 ]

JSON.stringify()와 JSON.parse()로 중첩된 객체(배열)를 깊은 복사를 할 수도 있다.

7. 국제화 API

Intl(Internationalization) API = I18N

숫자 간결하게 나타내기

const views = 9744642;

/* 한국어 */
let formatter = new Intl.NumberFormat("ko");
let formattedViews = formatter.format(views);
console.log(formattedViews); 
// 9,744,642

formatter = new Intl.NumberFormat("ko", { notation: "compact" });
formattedViews = formatter.format(views);
console.log(formattedViews); 
// 974만

/* 영어 */
formatter = new Intl.NumberFormat("en", { notation: "compact" });
formattedViews = formatter.format(views);
console.log(formattedViews); 
// 9.7M

formatter = new Intl.NumberFormat("en", {
  notation: "compact",
  compactDisplay: "long",
});
formattedViews = formatter.format(views);
console.log(formattedViews); 
// 9.7 million

/* navigator.language : 브라우저에서 사용자가 지정하는 언어에 따라 달라지도록 설정할 수도 있다. */
formatter = new Intl.NumberFormat(navigator.language, {
  notation: "compact",
  compactDisplay: "long",
});
formattedViews = formatter.format(views);
console.log(formattedViews);

가격 간결하게 나타내기

const price = 10000;

let formatter = new Intl.NumberFormat("ko", {
  style: "currency",
  currency: "krw",
  notation: "compact",
});
let formattedPrice = formatter.format(price);
console.log(formattedPrice); 
// ₩1만

formatter = new Intl.NumberFormat("ko", {
  style: "currency",
  currency: "krw",
});
formattedPrice = formatter.format(price);
console.log(formattedPrice); 
// ₩10,000

formatter = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency: "usd",
});
formattedPrice = formatter.format(price);
console.log(formattedPrice); 
// $10,000.00

상대시간 똑똑하게 나타내기

let formatter = new Intl.RelativeTimeFormat("en");

/* 상대적인 날짜 나타내기 */
let formattedDay = formatter.format(1, "day");
console.log(formattedDay); 
// in 1 day

formattedDay = formatter.format(2, "day");
console.log(formattedDay); 
// in 2 days

formattedDay = formatter.format(-1, "day");
console.log(formattedDay); 
// 1 day ago

formattedDay = formatter.format(-2, "day");
console.log(formattedDay); 
// 2 days ago
/* 두 번째 인자 numeric 지정 */
let formatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" });

formattedDay = formatter.format(1, "day");
console.log(formattedDay); 
// tomorrow

formattedDay = formatter.format(2, "day");
console.log(formattedDay); 
// in 2 days

formattedDay = formatter.format(-1, "day");
console.log(formattedDay); 
// yesterday

formattedDay = formatter.format(-2, "day");
console.log(formattedDay); 
// 2 days ago
/* 한국어 */
let formatter = new Intl.RelativeTimeFormat("ko", { numeric: "auto" });

formattedDay = formatter.format(1, "day");
console.log(formattedDay); // 내일

formattedDay = formatter.format(2, "day");
console.log(formattedDay); // 모레

formattedDay = formatter.format(-1, "day");
console.log(formattedDay); // 어제

formattedDay = formatter.format(-2, "day");
console.log(formattedDay); // 그저께
/* 사용 예제 */
const formatter = new Intl.RelativeTimeFormat("ko", { numeric: "auto" });

const today = new Date();
const started = new Date(2014, 03, 02);
const daysPassed = Math.ceil((today - started) / (1000 * 60 * 60 * 24));
console.log(`사귄 날짜: ${formatter.format(daysPassed, "day")}`);
// 사귄 날짜: 3,247일 후

상대 시간 나타내는데 유용한 라이브러리 소개

깃허브 timeago.js

날짜/시간 제대로 포맷하기

const date = new Date(2019, 10, 12);

/* toString 메서드 */
const strDate = date.toString();
console.log(strDate); 
// Tue Nov 12 2019 00:00:00 GMT+0900 (Korean Standard Time)

let IntlDate = new Intl.DateTimeFormat("en-US").format(date);
console.log(IntlDate); 
// 11/12/2019

IntlDate = new Intl.DateTimeFormat("ko").format(date);
console.log(IntlDate);
// 12.11.2019

IntlDate = new Intl.DateTimeFormat("de").format(date);
console.log(IntlDate); 
// 12.11.2019

/* toLocaleDateString 메서드가 동일한 기능을 한다. */
let localDate = date.toLocaleDateString();
console.log(localDate); 
// 11/12/2019

localDate = date.toLocaleDateString("ko");
console.log(localDate); 
// 2019. 11. 12.

/* 두 번째 파라미터로 스타일 설정이 가능하다 */
localDate = date.toLocaleString("en", {
  dateStyle: "full",
  timeStyle: "long",
});
console.log(localDate);
// Tuesday, November 12, 2019 at 12:00:00 AM GMT+9

localDate = date.toLocaleString("ko", {
  minute: "numeric",
  hour: "numeric",
  day: "numeric",
  month: "long",
  year: "numeric",
  weekday: "short",
});
console.log(localDate);
// 2019년 11월 12일 (화) 오전 12:00

8. 콘솔 API

다양한 console API 사이트

log /info /warn /error

dir / table

console.dir(rabbit, { depth: 0 });
// { name: 'tori', age: 9, owner: [Object] }

console.table(rabbit);
/*
┌─────────┬────────┬────────────────────────────────────┬────────┐
│ (index) │  name  │               family               │ Values │
├─────────┼────────┼────────────────────────────────────┼────────┤
│  name   │        │                                    │ 'tori' │
│   age   │        │                                    │   9    │
│  owner  │ 'Jake' │ { father: 'Mike', mother: 'Jane' } │        │
└─────────┴────────┴────────────────────────────────────┴────────┘ */

group

console.group("쇼핑몰 로그");
  console.log("로그인 됐는지 확인");

  console.group("회원 관련 작업");
    console.log("아이디 확인");
    console.log("비밀번호 확인");
  console.groupEnd();
  
  console.group("상품 관련 작업");
    console.log("가격 변동 확인");
    console.log("재고 유무 확인");
  console.groupEnd();

console.groupEnd();
/*
  회원 관련 작업
    아이디 확인
    비밀번호 확인
  상품 관련 작업
    가격 변동 확인
    재고 유무 확인
  */

console.groupCollapsed();
console.group와 동일하지만 처음부터 '접어서' 표시되고, 클릭하면 펼쳐진다.
node.js에서는 console.group와 동일하다.

assert

false 일때만 출력된다.

time / count / trace

  • console.time 호출된 시간을 기록한다. (아무것도 출력하지 않는다.)
    • console.timeEnd console.time이 호출 된 시간부터 경과된 시간을 출력한다.
    • console.timeLog console.time이 호출 된 시간부터 경과된 시간을 출력한다. 여러번 재사용할 수 있다.
  • consle.count 함수가 몇 번 호출됐는지 카운트해준다.
    • console.countReset() 카운트를 리셋한다.
  • console.trace 함수가 어디서 호출됐는지 출력해준다.
console.time("작업1");
for (let i = 0; i < 100000; i++) {}
console.timeEnd("작업1");
// 작업1: 1.271ms

console.time("반복작업");
for (let i = 0; i < 3; i++) {
  console.timeLog("반복작업");
}
console.timeEnd("반복작업");
/* 반복작업: 0.019ms
반복작업: 0.056ms
반복작업: 0.201ms
반복작업: 0.229ms */


function a() {
  console.count("a function");
}
a();
a();
console.countReset("a function");
a();
/* a function: 1
a function: 2
a function: 1 */


function f1() {
  f2();
}
function f2() {
  f3();
}
function f3() {
  console.trace();
  console.log("I'm here :o ~! ");
}
f1();
/*
Trace
    at f3 (/Users/snow/Desktop/Study/JavaScript 스터디/11장 표준라이브러리.js:91:11)
    at f2 (/Users/snow/Desktop/Study/JavaScript 스터디/11장 표준라이브러리.js:88:3)
    at f1 (/Users/snow/Desktop/Study/JavaScript 스터디/11장 표준라이브러리.js:85:3)
    at Object.<anonymous> (/Users/snow/Desktop/Study/JavaScript 스터디/11장 표준라이브러리.js:94:1)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47
I'm here :o ~! 
*/

console.clear()

콘솔창에서 전체 내역 지우기

css 적용 %c

콘솔 출력 형식

console 함수의 첫 번째 인자에 아래 표시의 문자열을 입력하면 형식 문자열로 취급한다.

표시의미
%s문자열
%i숫자 (정수가 아닌 부분 버림)
%d, %f숫자
%o, %O객체
%ccss 스타일로 해석

const name = "코난";
const job = "탐정";
const age = 10;
const score = { kor: 90, math: 80, eng: 70 };
console.log(
  "내 이름은 %s, %s이죠. %d살 입니다. 시험 점수는 %o 입니다.",
  name, job, age, score
); 
// 내 이름은 코난, 탐정이죠. 10살 입니다. 시험 점수는 { kor: 90, math: 80, eng: 70 } 입니다.

9. URL API

URL API 표준화 사이트

URL 객체는 URL() 생성자에 절대 URL을 문자열로 전달해 생성한다.
또는 상대 URL을 첫 번째 인자로 전달하고 기준이 되는 절대 URL을 두 번째 인자로 전달한다.

href 프로퍼티

10. 타이머

setTimeout

setTimeout(콜백함수, 시간) 일정 시간이 지난 후 콜백 함수를 호출한다.
clearTimeout()으로 함수 호출을 취소할 수 있다.

  • 두 번째 파라미터를 생략하면 기본 값은 0이다.
    • 즉시 호출된다는 의미는 아니며, 브라우저가 다른 이벤트 때문에 바쁜 경우 수초 후 콜백함수가 호출 될 수도 있다.

setInterval

setInterval(콜백함수, 시간) 일정 시간마다 콜백함수를 반복적으로 호출한다.
clearInterval()으로 함수 호출을 취소할 수 있다.

/* 콘솔에 디지털 시계를 표현하는 사용 예제 */

// 매 초마다 콘솔을 비우고, 현재 시간 출력 
let clock = setInterval(()=>{
  console.clear();
  console.log(new Date().toLocaleTimeString());
}, 1000);

// 10초 뒤 반복을 멈춥니다.
setTimeout(()=>{ clearInterval(clock);}, 10000);

참고 자료 : 정규표현식 , 더이상 미루지 말자 🤩
MDN Intl
자바스크립트로 코딩할때 꿀팁 🍯🐝
5분 안에 JavaScript 콘솔 API
콘솔 로그 제대로 쓰고 있을까? 🤔
console 에 이렇게 다양한 기능이? 아직도 console.log 만 사용하세요?

profile
React, Next.js, TypeScript 로 개발 중인 프론트엔드 개발자

0개의 댓글