구조 분해 할당(Destructuring Assignment)? 배열이나 객체의 구조를 분해하여 분해된 값을 개별 변수에 담는 표현식 배열 구조 분해 변수를 선언하고 할당하는 과정 한 번에 가능 one, two, three는 우변에 위치한 arr의 값을 차례대로 할당받음 const arr = [1, 2, 3, 4, 5] const [one, two, three] = arr console.log(one, two, three) 1 2 3 객체 구조 분해 객체를 할당할 때는 분해하려는 프로퍼티의 키 사용 const obj = { x: 10, y: 20, z: 30 } const { x, y, z } = obj console.log(x, y, z) 10 20 30 변수 이름 변경 분해한 키에 :(콜론)을 붙이고..
아래와 같은 객체를 Object.entries()를 사용하여 배열로 변환해보자. const obj = { x: 10, y: 20, z: 30 } Object.entries()만 사용 const arr = Object.entries(obj) console.log(arr) [ [ 'x', 10 ], [ 'y', 20 ], [ 'z', 30 ] ] map과 같이 사용 const arr = Object.entries(obj).map(([key, value]) => ({key, value})) console.log(arr) [ { key: 'x', value: 10 }, { key: 'y', value: 20 }, { key: 'z', value: 30 } ] 배열을 객체로 변환하기 위해서는? Object.fro..
Prisma 프로젝트 설정 폴더 만들고 npm 초기화 mkdir prisma cd prisma npm init -y prisma, ts-node, @types/node 설치 npm install prisma @prisma/client typescript ts-node @types/node --save-dev prisma 초기화 npx prisma init 초기화하면 prisma 폴더와 .env 파일 생성 됨 .env에 환경변수 설정 DATABASE_URL="디비종류://유저이름:패스워드@localhost:포트번호/디비이름" DB_PORT=5432 DB_USER=test DB_PASSWORD=test DB_HOST=localhost DATABASE=postgres DB_SCHEMA=public DATABA..
단독으로 쓰거나 함수 안에서의 this Node.js에서는 global 브라우저에서는 window 엄격 모드에서는 undefined function f1() { return this; } // 브라우저 console.log(f1()); // window console.log(this); // window f1() === window; // true // Node.js console.log(f1()); // global console.log(this); // global f1() === global; // true function f2(){ "use strict"; // 엄격 모드 return this; } console.log(f2()); // undefined f2() === undefined; // ..
Math.round() 입력된 숫자를 소수점 반올림하여 반환 Math.round(4.5) // 5 Math.round(9.2) // 9 Math.round(-4.5) // -4 Math.round(-4.9) // -5 Math.round(-9.2) // -9 Math.ceil() 입력된 숫자를 소수점 올림하여 반환 Math.ceil(4.2) // 5 Math.ceil(9.9) // 10 Math.ceil(-4.2) // -4 Math.ceil(-9.9) // -9 Math.floor() 입력된 숫자를 소수점 내림하여 반환 Math.floor(4.7) // 4 Math.floor(9.2) // 9 Math.floor(-4.2) // -5 Math.floor(-4.7) // -5 Math.floor(-9.2..
ES2019에 추가된 flat(), flatMap()에 대해 알아보자. flat() 지정한 깊이(기본값 1)까지 하위 배열을 평탄화한 새로운 배열로 생성하여 반환한다. 배열의 구멍도 제거한다. 구문 const newArr = arr.flat([depth]) 예제 const arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] const arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 1..
특정 IP로만 접근을 허용하거나 차단해야 하는 경우가 있다. Node.js와 Express.js 환경에서 어떻게 하는지 알아보자. 특정 IP 설정 const ips = ['127.0.0.1','127.0.0.2']; 접근 허용 const allowIPs = (ips) => { return (req, res, next) => { const clientIP = req.headers['x-forwarded-for'] || req.socket.remoteAddress; if (ips.includes(clientIP)) { next(); } else { res.status(403).send('접근 차단'); } }; }; app.use(allowIPs(ips)); 접근 차단 const blockIPs = (ips..
HTTP Request를 위한 방법 중 Fetch, Axios에 대해 알아보자. Fetch fetch("https://localhost:3000/user", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id: "hj1", name: "hjkang", }), }).then((response) => console.log(response)); 장점 내장 라이브러리이므로 별도로 import 할 필요가 없다. 내장 라이브러리이므로 업데이트에 따른 에러 방지가 가능하다. Promise를 기반으로 만들어져서 다루기 쉽다. 단점 지원하지 않는 브라우저가 존재한다.(ex. IE11) 네트워크 에러 발생 ..
console.time()이란? 코드나 함수 실행에 걸리는 시간을 계산 할 때 타이머로 사용 console.timeEnd()이란? 타이머를 종료하고 걸린 시간을 밀리초 단위로 출력 사용 방법 매개변수인 label은 타이머의 이름으로 자유롭게 지정 가능 입력하지 않을 시 default label로 자동 지정 // 타이머 시작 console.time(label) // 시간 측정이 필요한 코드 작성 // 타이머 종료 console.timeEnd(label) 예시 1부터 999999 까지의 숫자를 더하는 add() 함수의 실행 시간 계산 타이머 이름은 "test timer"로 하였음 function add() { let sum = 0; for (let i = 1; i < 1000000; i++) { sum +=..
많은 사람들이 JavaScript 코드 디버깅 할 때 console.log() 를 사용한다. console.table()을 활용하여 좀 더 효율적으로 디버깅해보자. console.table()이란? 배열과 객체를 테이블 형식으로 콘솔에 출력 테이블의 헤더를 클릭하여 정렬도 가능 사용 방법 1. 배열 const fruits = ['apple', 'banana', 'mango'] console.table(fruits) 2. 배열의 배열 const names = [['Kang', 'HyeonJi'], ['Hong', 'GilDong'], ['Kim', 'Test']] console.table(names) 3. 객체 const user = { name: "Kang HyeonJi", age: 30, } conso..