유튜브 강의
자바스크립트 9. 유용한 10가지 배열 함수들. Array APIs 총정리 | 프론트엔드 개발자 입문편 ( JavaScript ES6)
'use strict'
// q1. make a string out of an array
{
const fruits = ['apple', 'banana', 'orange'];
let a1 = '';
for (const value of fruits) {
a1 += value;
}
console.log(a1);
const r1 = fruits.join();
const r1_1 = fruits.toString();
console.log(r1);
console.log(r1_1);
}
// q2. make an array out of a string
{
const fruits = 'apple, kiwi, banana, cherry';
const a2 = fruits.split(',');
console.log(a2);
}
// q3. make this array look like this: [5,4,3,2,1]
{
const array = [1,2,3,4,5];
const a3 = array.reverse();
console.log(a3);
console.log(array); // array 자체를 변경시킴
}
// q4. make new array without the first two elements
{
const array = [1,2,3,4,5];
const a4 = array.slice(2)
console.log(a4)
console.log(array)
// splice : 배열 자체를 수정
// slice : 배열 중 원하는 부분만 가져옴
}
class Student {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}
const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88)
];
// q5. find a student with the score 90
{
// find : parameter로 받은 함수 결과가 true이면 해당하는 element 반환
const r5 = students.find((student) => student.score === 90);
console.log(r5);
}
// q6. make an array of enrolled students
{
const a6 = students.filter((student) => student.enrolled);
console.log(a6);
}
// q7. make an array containing only the students' scores
// result should be: [45, 80, 90, 66, 88]
{
const a7 = students.map((student) => student.score)
console.log(a7)
}
// q8. check if there is a student with the score lower than 50
{
const a8 = students.some((student) => student.score < 50)
console.log(a8)
const r8 = !students.every((student) => student.score >= 50)
console.log(r8)
}
// q9. compute students' average score
{
const r9 = students.reduce((prev, curr) => prev + curr.score, 0)
console.log(r9 / students.length)
}
// q10. make a string containing all the scores
// result should be: '45, 80, 90, 66, 88'
{
const a10 = students
.map((student) => student.score)
.join();
console.log(a10)
}
// bonus do q10 sorted in ascending order
// result should be: '45, 66, 80, 88, 90'
{
const aBonus = students
.map((student) => student.score)
.sort((a,b) => a - b)
.join();
console.log(aBonus);
}
유튜브 강의
자바스크립트 10. JSON 개념 정리 와 활용방법 및 유용한 사이트 공유 JavaScript JSON | 프론트엔드 개발자 입문편 (JavaScript ES6)
// object to JSON
// stringify(obj)
let json = JSON.stringify(true);
console.log(json);
json = JSON.stringify(['apple', 'banana']);
console.log(json);
// object
const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: () => {
console.log(`${name} can jump`);
}
};
json = JSON.stringify(rabbit);
console.log(json);
json = JSON.stringify(rabbit, ['name', 'color']);
console.log(json)
json = JSON.stringify(rabbit, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'name' ? 'ellie': value;
})
console.log(json);
// JSON to object
// parse(json)
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);
rabbit.jump();
// obj.jump(); // error
console.log(rabbit.birthDate.getDate());
// console.log(obj.birthDate.getDate()); // error
const obj2 = JSON.parse(json, (key, value) => {
console.log(`key: ${key}, value: ${value}`);
return key === 'birthDate' ? new Date(value) : value;
})
console.log(rabbit.birthDate.getDate());
console.log(obj2.birthDate.getDate())
유용한 사이트
json 다른 곳 찾아주는 사이트
디버깅에 사용
JSON Diff - The semantic JSON compare tool
json format 만들어주는 사이트
Json Beautifier - Json Formatter | Json Viewer | Json Editor
json을 object로 확인할 수 있는 사이트
Json Parser Online
유효한 json인지 확인할 수 있는 사이트
JSON Formatter & Validator
유튜브 강의
자바스크립트 11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback | 프론트엔드 개발자 입문편 (JavaScript ES6)
Javascript는 동기적(symchronous)
Asynchronous
'use strict';
// JavaScript is symchronous
// Execute the code block in order after hoisting.
console.log('1');
setTimeout(function () {
console.log('2');
}, 1000);
console.log('2');
console.log('3');
// Synchronous callback
function printImmediately(print) {
print();
}
printImmediately(() => console.log('hello'));
// Asynchronous callback
function printWithDelay(print, timeout) {
setTimeout(print, timeout);
}
printWithDelay(() => console.log('async callback'), 2000);
// Callback Hell example
class UserStorage {
loginUser(id, password, onSuccess, onError) {
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
onSuccess(id);
} else {
onError(new Error('not found'));
}
}, 2000);
}
getRoles(user, onSuccess, onError) {
setTimeout(() => {
if (user === 'ellie') {
onSuccess({name: 'ellie', role: 'admin'});
} else {
onError(new Error('no access'));
}
}, 1000);
}
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(
id,
password,
user => {
userStorage.getRoles(
user,
userWithRole => {
alert(`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`)
},
error => {}
);
},
(error) => {
})
유튜브 강의
자바스크립트 12. 프로미스 개념부터 활용까지 JavaScript Promise | 프론트엔드 개발자 입문편 (JavaScript ES6)
// producer
// when new promise is created, the executor runs automatically.
const promise = new Promise((resolve, reject) => {
// doing some heavy work (network, read files)
console.log('doing something...');
setTimeout(() => {
resolve('ellie');
// reject(new Error('no network'));
}, 2000);
})
// consumer
// then, catch, finally
promise
.then((value) => {
console.log(value);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log('finally');
})
// Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
setTimeout(() => resolve(1), 1000);
});
fetchNumber
.then(num => num * 2)
.then(num => num * 3)
.then(num => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num - 1), 1000);
});
})
.then(num => console.log(num));
// Error Handling
const getHen = () =>
new Promise((resolve, reject) => {
setTimeout(() => resolve('🐔'), 1000);
});
const getEgg = hen =>
new Promise((resolve, reject) => {
setTimeout(() => reject(new Error(`${hen} => 🥚`)), 1000);
});
const cook = egg =>
new Promise((resolve, reject) => {
setTimeout(() => resolve(`${egg} => 🍳`), 1000);
});
getHen() //
.then(getEgg)
.catch(error => {
return '🍗';
})
.then(cook)
.then(console.log)
.catch(console.log);
'use strict'
// Callback Hell example
class UserStorage {
loginUser(id, password) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (
(id === 'ellie' && password === 'dream') ||
(id === 'coder' && password === 'academy')
) {
resolve(id);
} else {
reject(new Error('not found'));
}
}, 2000);
});
}
getRoles(user) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (user === 'ellie') {
resolve({name: 'ellie', role: 'admin'});
} else {
reject(new Error('no access'));
}
}, 1000);
})
}
}
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');
userStorage.loginUser(id, password)
.then(userStorage.getRoles)
.then(user => alert(`Hello ${user.name}, you have a ${user.role} role`))
.catch(console.log);
유튜브 강의
자바스크립트 13. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs | 프론트엔드 개발자 입문편 (JavaScript ES6)
// async
async function fetchUser() {
// do network request in 10 secs
return 'ellie';
}
const user = fetchUser();
user.then(console.log);
console.log(user);
// await
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
async function getApple() {
await delay(3000);
return 'apple';
}
async function getBanana() {
await delay(3000);
return 'banana';
}
function getBanana() {
return delay(3000)
.then(() => 'banana');
}
function pickFruits() {
return getApple()
.then(apple => {
return getBanana().then(banana => `${apple} + ${banana}`)
})
}
pickFruits().then(console.log);
// 위 함수에 async 사용
async function pickfruits() {
const applePromise = getApple();
const bananaPromise = getBanana();
const apple = await applePromise;
const banana = await bananaPromise;
return `${apple} + ${banana}`;
}
// useful Promise APIs
function pickAllFruits() {
return Promise.all([getApple(), getBanana()]).then(fruits => fruits.join(' + '));
}
pickAllFruits().then(console.log);
function pickOnlyOne() {
return Promise.race([getApple(), getBanana()]);
}
pickOnlyOne().then(console.log);