2장 알아두어야 할 자바스크립트
2.1 ES2015+
2.1.1 const, let
var에서 const, let이 대체 => 이 둘의 특징은 블록 스코프(범위)
if (true) {
const y = 3;
}
console.log(y) // Uncaught ReferenceError: y is not defined
// y가 선언된 블록 밖을 벗어났기 때문에 찾지 못함
const : 한 번 값을 할당하면 다른 값을 할당 할 수 x
let : 한 번 값을 할당하고 다른 값 할당 가능
2.1.2 템플릿 문자열
`문자열 ${변수}` 형식으로 변수를 더하기 기호 없이 문자열에 넣음, 큰따옴표나 작음따옴표도 이스케이프 없이 사용 가능
2.1.3 객체 리터럴
// 기존 코드
var sayNode = function() {
console.log('Node');
};
var es = 'ES';
var oldObject = {
sayJS: function () {
console.log('JS');
},
sayNode: sayNode,
};
oldObject[es + 6] - 'Fantastic';
oldObject.sayNode(); // Node
oldObject.sayJS(); // JS
console.log(oldObject.ES6); // Fantastic
// 변경된 코드
const sayNode = () => {
console.log('Node');
};
const newObject = {
sayJS() { // 객체 매서드에 함수 연결
console.log('JS');
},
sayNode, // 속성명과 변수명이 동일한 경우 한 번만 써도 됨
[es + 6]: 'Fantastic', // 객체의 속성명은 동적으로 생성되는데 객체 리터럴 안에 동적 속성 선언 가능해짐
};
newObject.sayNode(); // Node
newOjbect.sayJS(); // JS
console.log(newObject.ES6)
2.1.4 화살표 함수
// 기존의 function() {}
function add1(x, y) {
return x + y;
}
// 화살표 함수 1
const add2 = (x, y) => {
return x + y;
};
// 화살표 함수 2 (return문 제거)
const add3 = (x, y) => x + y;
// 기존의 function() {}
function not1(x) {
return !x;
}
// 화살표 함수 3
const not2 = x => !x;
2.1.5 구조분해 할당
[예시]
const array = ['nodejs', {}, 10, true];
const [node, obj, , bool] = array;
2.1.6 클래스
[클래스 기반 코드]
class Human {
constructor(type = "human") {
this.type = type;
}
static isHuman(human) {
return human instanceof Human;
}
breathe() {
alert("h-a-a-a-m");
}
}
class Zero extends Human {
constructor(type, firstName, lastName) {
super(type);
this.firstName = firstName;
this.lastName = lastName;
}
sayName() {
super.breathe();
alert(`${this.firstName} ${this.lastName}`);
}
}
const newZero = new Zero("human", "Zero", "Cho");
Human.isHuman(newZero); // true
2.1.7 프로미스
프로미스 - 실행은 바로 하되 결괏값은 나중에 받는 객체, 결괏값은 then을 붙였을 때 받게 됨
[프로미스 기본 규칙]
const condition = true; // true면 resolve, false면 reject
const promise = new Promise((resolve, reject) => {
if (condition) {
resolve("성공");
} else {
reject("실패");
}
});
// 다른 코드가 들어갈 수 있음
promise
.then((message) => {
console.log(message); // 성공(resolve)한 경우 실행
})
.catch((error) => {
console.error(error); // 실패(reject)한 경우 실행
})
.finally(() => { // 끝나고 무조건 실행
console.log('무조건');
});
[then이나 catch에서 다시 다른 then이나 catch 붙이기]
promise
.then((message) => {
return new Promise((resolve, reject) => {
resolve(message);
});
})
.then((message2) => {
console.log(message2);
return new Promise((resolve, reject) => {
resolve(message2);
});
})
.then((message3) => {
console.log(message3);
})
.catch((error) => {
console.error(error);
});
[프로미스 여러 개를 한 번에 실행하기]
Promise 중 하나라도 reject 되면 catch로 넘어감
const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
Promise.all([promise1, promise2])
.then((result) => {
console.log(result); // ['성공1', '성공2']
})
.catch((error) => {
console.error(error);
});
2.1.8 async/await
[프로미스 코드 -> awync/await 문법 사용]
// 프로미스 코드
function findAndSaveUser(Users) {
Users.findOne({})
.then((user) => {
user.name = 'zero';
return user.save();
})
.hen((user) => {
return Users.findOne({ gender: 'm'});
})
.then((user) => {
// 생략
})
.catch(err => {
console.error(err);
})
}
// async/await 문법 사용
async function findAndSaveUser(Users) {
try {
let user = await Users.findOne({});
user.name = 'zero';
user = await user.save();
user = await Users.findOne({ gender: 'm'});
} catch (error) {
console.error(error);
}
}
// 화살표 함수 사용한 async/await
const findAndSaveUser = async (Users) => {
try {
let user = await Users.findOne({});
user.name = 'zero';
user = await user.save();
user = await Users.findOne({ gender: 'm'});
} catch (error) {
console.error(error);
}
};
[for문과 async/await을 같이 써서 프로미스 순차적 실행]
const promise1 = Promise.resolve('성공1');
const promise2 = Promise.resolve('성공2');
(async () => {
for await (promise of [promise1, promise2]) {
console.log(promise);
}
})();
2.2 프런트엔드 자바스크립트
2.2.1 AJAX
AJAX : 비동기적 웹 서비스를 개발할 때 사용하는 기법 - 페이지 이동 없이 서버에 요청을 보내고 응답을 받는 기술 => jQuery, axios 같은 라이브러리 이용해서 보냄
[프런트엔드에서 AJAX 사용하기 위한 방법]
<!-- front.html -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
// 여기에 예제 코드를 넣으세요.
</script>
- GET 요청 - axios.get 함수의 인수로 요청을 보낼 주소를 넣으면 됨
// 프로미스 코드
axios.get('https://www.zerocho.com/api/get')
.then((result) => {
console.log(result);
console.log(result.data); // result.data : 서버로부터 보낸 데이터
})
.catch((error) => {
console.error(error);
});
// async/await 방식
(async () => {
try {
const result = await axios.get('https://www/zerocho/com/api/get');
console.log(result);
console.log(result.data); // result.data : 서버로부터 보낸 데이터
} catch (error) {
console.error(error);
}
})();
- POST 요청 - axios.post 함수의 인수로 요청을 보낼 주소와 보낼 데이터를 넣으면 됨
// async/await 방식
(async () => {
try {
const result = await axios.post('https://zerocho.com/api/post/json', {
name: 'zerocho',
birth: 1994,
});
console.log(result);
console.log(result.data); // result.data : 서버로부터 보낸 데이터
} catch (error) {
console.error(error);
}
})();
2.2.2 FormData
FormData : HTML from 태그의 데이터를 동적으로 제어할 수 있는 기능, AJAX와 함께 사용
[메서드]
- append(키, 값) : 데이터를 저장, 키 하나에 여러 개의 값을 추가해도 됨
- has(키) : 주어진 키에 해당하는 값이 있는지 여부 알려줌
- get(키) : 주어진 키에 해당하는 값 하나를 가져옴
- getAll(키) : 주어진 키에 해당하는 모든 값을 가져옴
- delete(키) : 현재 키를 제거
- set(키, 값) : 현재 키를 수정
[axios로 폼 데이터를 서버에 보내기]
(async () => {
try {
const formData = new FormData();
formData.append('name', 'zerocho');
formData.append('birth', 1994);
const result = await axios.post('https://www.zerocho.com/api/post/formdata', formData);
console.log(result);
console.log(result.data);
} catch (error) {
console.error(error);
}
})();
2.2.3 encodeURIComponent, decodeURIComponent
encodeURIComponent(한글 주소) : 서버가 한글 주소를 이해하지 못할 때 한글 주소 부분만 감쌈
decodeURIComponent(변환된 문자열) : 변환된 주소 문자열을 다시 한글로 복구
(async () => {
try {
const result = await axios.get(`https://www.zerocho.com/api/search/${encodeURIComponent('노드')}`);
console.log(result);
console.log(result.data);
} catch (error) {
console.error(error);
}
})();
decodeURIComponent(문자열);
2.2.4 데이터 속성과 dataset
서버에서 보내준 데이터 중 프런트엔드에서 HTML과 관련된 데이터를 저장하는 공식적인 방법 => 데이터 속성
<!-- data-로 시작하는 것이 데이터 속성 -->
<ul>
<li data-id="1" data-user-job="programmer">Zero</li>
<li data-id="2" data-user-job="designer">Nero</li>
<li data-id="3" data-user-job="programmer">Hero</li>
<li data-id="4" data-user-job="ceo">Kero</li>
</ul>
<script>
// dataset 속성을 통해 li 태그의 데이터 속성에 접근
console.log(document.querySelector('li').dataset);
// {id: '1', userJob: 'programmer'}
</script>
Author And Source
이 문제에 관하여(2장 알아두어야 할 자바스크립트), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@rosesua318/2장-알아두어야-할-자바스크립트저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)