※과제로 인하여 정리 기간이 늦어졌습니다..
수업내용 위주의 정리입니다.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)); // ["camel", "duck"]
console.log(animals.slice(-2)); // ["duck", "elephant"]
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
console.log(words[3]); // "fox"
const chars = str.split('');
console.log(chars[8]); // "k"
const array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat')); // true
console.log(pets.includes('at')); // false
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
console.log(`"${searchTerm}" is ${indexOfFirst}`);
// "dog" is 40
function milliseconds(x) {
if (isNaN(x)) {
return 'Not a Number!';
}
return x * 1000;
}
console.log(milliseconds('100F')); //"Not a Number!"
console.log(milliseconds('0.0314'));// 31.4
function roughScale(x, base) {
const parsed = parseInt(x, base);
if (isNaN(parsed)) { return 0; }
return parsed * 100;
}
console.log(roughScale('32.5', 10)); // 3200
function circumference(r) {
return parseFloat(r) * 2
}
console.log(circumference(4.567)); // 9.134
// callback 사용(화살표함수, return있음, 요소 갯수만큼 반복)
const arr = [1, 2, 3, 4];
console.log(
arr.every(item => item < 5) // true
)
const arr = [1, 2, 3, 4];
console.log(
arr.filter(item => item < 3) // [1, 2]
)
const users = [
{name: 'Hun', age: 27},
{name: 'Hero', age: 85}
];
const foundUser = users.find(user => user.name === "Hun");
console.log(foundUser);
const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];
const findIndex = fruits.find(fruit => {
return /^B/.test(fruit); // /^B/대문자 B로 시작하는 문자 데이터
})
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join()); // "Fire,Air,Water"
console.log(elements.join('')); // "FireAirWater"
console.log(elements.join('-')); // "Fire-Air-Water"
const arr = ['AR', '패션','스포츠', '인테리어'];
console.log(
arr.map(item => {
return {
name: item
}
})
);
// (4) [{name: 'AR'}, {name: '패션'}, {name: '스포츠'}, {name: '인테리어'}]
const arr2 = [1, 2, 3, 4];
console.log(
arr2.map((item,index) => {
console.log(index) // 0 1 2 3
return item * 2; // [2, 3, 6, 8]
})
)
const arr1 = [1, 2, 3, 4];
const arr2 = [1, 2, 3, 4];
console.log(
arr1.pop(); // 4
arr2.shift(); // 1
)
console.log(arr1) // [1, 2, 3]
console.log(arr2) // [2, 3, 4]
const arr1 = [1, 2, 3, 4];
const arr2 = [1, 2, 3, 4];
console.log(
arr1.push(99, 7, 1421); // 7
arr2.unshift(99, 7, 1421); // 7
)
console.log(arr1) // [1, 2, 3, 4, 99, 7, 1421]
console.log(arr2) // [99, 7, 1421, 1, 2, 3, 4]
// 1. 예제
const arr = [1, 2, 3, 4];
// reduce(accumlator(누적 값), currentValue(현재 값))
const sum = arr.reduce((acc, cur) => { // 2. cur = 1부터 시작
//callback함수
return acc + cur // 3. 값이 acc로 넘어감
}, 0); // 뒤에 숫자는 초기 값, 1. acc로 들어감
console.log(sum); // 10
const arr = [1, 2, 3, 4];
console.log(arr.reverse()); // [4, 3, 2, 1]
const user = {
name: 'Hun',
age: 27,
isValid: true
}
// const e = user.name;
// const a = user.age;
// const i = user.isValid;
// 구조 분해 할당
const {
name: e,
age: a,
isValid: i,
email: x= 'the'
} = user
console.log(e, a, i, x) // Hun 27 true the
const {
name: e,
...rest
} = user
console.log(e, rest) // rest는 나머지 전부 꺼내서 객체 데이터 형태로 꺼내온다.
const user = {
name: 'Hun',
age: 27
}
for (const [k, v] of Object.entries(user)) {
console.log(k, v) // name Hun
// age 27
}
나열되어 있기 때문에 순서를 맞춰줘야 한다!
const aee = [1, 2, 3];
const [x, y, z] = arr
console.log(x, y, z) // 1 2 3
const [,,,z] = arr2
console.log(z) // 3
// 값을 맞교환(순서만)바꿀 때 유용하게 사용 가능
let a = 1
let b = 3
// const backup = a
// a = b
// b = backup
[b, a] = [a, b];
console.log(a) // 3
console.log(b) // 1
const arr = [1, 2, 3, 4, 5, 6, 7, 8]
const [x, y, ...r] = arr
console.log(x, y, r)
// 메모리
// |M1|M2|M3|M4|M5|M6|M7|M8|
const a = 1; // M1
let b = 1; // M1
b = 7; // M2
// M2는 현재 상태에서 가비지콜렉션이 비워준다.
// 근데 가비지 콜렉션이 언제 비워줄지 몰라서 메모리에 남아있을 수 있다.
// 메모리가 낭비되고 있다.
// 고로 메모리 관리를 잘 해줘야한다!
const a = 'A' // M1
let b = 'B' // M2
b = 123; // M3
// 직접적으로 메모리 관리를 할 수 없지만 상황에 맞게 정리를 해줄 수 있다.
let btnEl = document.querySelector('button') // M1, Element {}
const handler = event => { // M2, handler() => {}
console.log(123)
}
btnEl.addEventListener('click', handler) // M2
btnEl.removeEventListener('click', handler) // M2를 지워라, 메모리 관리
btnEl = null; // M3, 상황이 되서 필요가 없으면 M1을 가비지 컬렉션이 와서 비워준다.
// 메모리
// |M1|M2|M3|M4|M5|M6|M7|M8|
// 예시 1
const a = { x: 1 }; // M1: { x: }, M2: 1 => { x: M2 }
const b = a; //
b.x = 7; // M3: 7, { x: M3 }
// 예시 2
const a = { // M1: {x:M2 ,y:M3 }
x: 1, // M2: 1
y: [1, 2] // M3: [M2, M4]
} // M4: 2
const b = a.y // M3: [M2, M4]
b[0] = 7 // M5: 7 => M3: [M5, M4]
console.log(a.y) // [7, 2]
// 예시 3
const a = { // M1: {x: M2,y: M3, z: M4}
x: 1, // M2: 1
y: [1, 2], // M3: [M2, M4]
z: { a:2, b:3 } // M4: 2
} // M5: {a: M4, b:M6}
// M6: 3
const b = a.z // M7: {}
b.a = {} // M8: {}
동기는 순차적으로 처리를한다. 하나를 처리가 완전히 끝나야 다음으로 넘어간다.
비동기는 하나의 코드를 처리하고 있는 도중 다음 코드를 처리할 수 있다.
동기: 1 -> 끝 -> 2 -> 끝 -> 3 -> 끝 -> ..
비동기: 1 -> 2 -> 3 -> 끝 -> 4 -> ..
비동기 함수, then(): 값을 가지고 돌아오면 그때 실행하게 된다.
// 전송
fetch('https://www.omdbapi.com?apikey=7035c60c&s=frozen', {
method: 'GET' // 기본 메소드 GET, method에 다른 값도 사용 가능하다.
})
.then(res => res.json())
.then(res => {
console.log(res)
})
console.log(123)
하위호환성이 좋다.
axios({
url: 'https://www.omdbapi.com?apikey=7035c60c&s=frozen',
method: 'GET'
})
.then(res => console.log(res));
console.log(123)
같이 세트로 묶어서 사용해야 한다. 비동기 함수임을 선언한다. 동기처럼 처리할 수 있게 만들어 준다.
// 1. fetch 사용
async function getMovie() {
let res = await fetch('https://www.omdbapi.com?apikey=7035c60c&s=frozen')
res = await res.json()
console.log(res)
}
// 2. axios 사용
async function getMovie() {
const { data } = await axios({
url: 'https://www.omdbapi.com?apikey=7035c60c&s=frozen',
method: 'GET'
})
console.log(data)
}
원하는 정보를 OMDb API를 이용해서 빼보기
// 원하는 정보 빼오기?
// index.html
// <button></button>
// <div class="movies"></div>
const moviesEl = document.querySelector('.movies');
const anotherMoviesEl = document.querySelector('.another');
getMovie(1, moviesEl);
getMovie(1, anotherMoviesEl);
const btnEl = document.querySelector('button');
btnEl.addEventListener('click', () => {
getMovie(2, moviesEl);
});
async function getMovie(page, containerEl) {
const { data } = await axios({
url: `https://www.omdbapi.com?apikey=7035c60c&s=frozen&page=${this}`,
method: 'GET'
})
console.log(data);
const movies = data.Search;
renderMovies(movies);
};
function renderMovies(movies) {
movies.forEach(movie => {
console.log(movie);
const movieEl = document.createElement('div');
movieEl.textContent = movie.Title;
document.body.append(movieEl);
})
};