21~24일차 JavaScript 메소드, 숫자, 구조분해할당, 배열, 데이터, 비동기

변승훈·2022년 4월 29일
0

※과제로 인하여 정리 기간이 늦어졌습니다..
수업내용 위주의 정리입니다.

1. 표준 내장 객체(메소드)

1-1. 문자

  1. slice(): 배열의 시작부터 끝 까지(끝은 포함하지 않는다)에 대한 얕은 복사본을 새로운 배열 객체로 반환한다. 원본은 바뀌지 않는다.
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"]
  1. split(): String 객체를 지정한 구분자를 이용하여 여러 개의 문자열로 나눈다.
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"
  1. includes(): 배열이 특정 요소를 포함하고 있는지 판별한다.
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
 
  1. indexOf(): 호출한 String 객체에서 주어진 값과 일치하는 첫 번째 인덱스를 반환한다. 일치하는 값이 없다면 -1을 반환한다.
    str.indexOf(searchValue,[, fromindex]);
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

1-2. 숫자와 수학

  1. isNaN(), Nuber.isNaN(): 어떤 값이 NaN인지 판별한다.
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
  1. parseInt(), Number.parseInt(): 문자열 인자를 정수로 반환한다.
function roughScale(x, base) {
  const parsed = parseInt(x, base);
  if (isNaN(parsed)) { return 0; }
  return parsed * 100;
}

console.log(roughScale('32.5', 10));	// 3200
  1. parseFloat(), Number.parseFloat(): 주어진 값을 문자열로 변환한 후 소수점이 있는 실수로 반환한다.
function circumference(r) {
  return parseFloat(r) * 2
}

console.log(circumference(4.567)); // 9.134

1-3. 배열

  1. every(): ()안이 truthy여야 통과, 모든 요소가 주어진 판별 함수를 통과(truthy)하는지 테스트하는 메소드
// callback 사용(화살표함수, return있음, 요소 갯수만큼 반복)
const arr = [1, 2, 3, 4];
console.log(
  arr.every(item => item < 5)  // true
)
  1. filter(): 통과한 값들을 새로운 배열로 만든다.(기존 배열은 존재)
const arr = [1, 2, 3, 4];
console.log(
  arr.filter(item => item < 3)  // [1, 2]
)
  1. find(): 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환한다. 없으면 undefined를 반환한다.
const users = [
  {name: 'Hun', age: 27},
  {name: 'Hero', age: 85}
];
const foundUser = users.find(user => user.name === "Hun");
console.log(foundUser);
  1. findIndex(): 맨 처음 찾은 녀석의 "index" 번호를 반환한다.
const numbers = [1, 2, 3, 4];
const fruits = ['Apple', 'Banana', 'Cherry'];

const findIndex = fruits.find(fruit => {
  return /^B/.test(fruit);  // /^B/대문자 B로 시작하는 문자 데이터
})
  1. join(): 배열의 모든 요소를 연결해 하나의 "문자열"로 만든다.
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());		// "Fire,Air,Water"

console.log(elements.join(''));		// "FireAirWater"

console.log(elements.join('-'));	// "Fire-Air-Water"
  1. map(): 배열 내의 모든 요소에 반환된 데이터로 새로운 배열을 만들어 준다.
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]
  })
)
  1. pop(): 배열의 마지막 요소를 제거한다. 그 제거된 요소를 반환한다.
    원본이 수정된다.
  2. shift(): pop과 반대로 맨 앞의 요소를 제거하고 그 제거된 요소를 반환한다.
    원본이 수정된다.
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]
  1. push(): 배열의 끝에 하나 "이상"의 요소를 추가하고 배열의 "새로운 길이"를 반환한다.
  2. unshift(): 배열의 앞에 하나 "이상"의 요소를 추가하고 배열의 "새로운 길이"를 반환한다.
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. reduce(): 배열의 각 요소에 대해 주어진 함수를 실행하고, 하나의 결과 값을 반환합니다.

// 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
  1. reverse(): 배열의 순서를 뒤집는다(반전시킨다).
const arr = [1, 2, 3, 4];

console.log(arr.reverse());	// [4, 3, 2, 1]

2. 구조 분해 할당

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
}

2-2. 배열

나열되어 있기 때문에 순서를 맞춰줘야 한다!

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)

3. 데이터의 불변성과 가변성

  • 참조형 데이터 : 객체 배열 함수
  • 원시형 데이터 : 나머지

3-1. 원시형 : 똑같이 생긴 것은 같은 메모리 주소를 참조한다.

// 메모리
// |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을 가비지 컬렉션이 와서 비워준다.

3-2. 참조형

// 메모리
// |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: {}

4. 비동기

동기는 순차적으로 처리를한다. 하나를 처리가 완전히 끝나야 다음으로 넘어간다.
비동기는 하나의 코드를 처리하고 있는 도중 다음 코드를 처리할 수 있다.

동기: 1 -> 끝 -> 2 -> 끝 -> 3 -> 끝 -> ..
비동기: 1 -> 2 -> 3 -> 끝 -> 4 -> ..

4-1. fetch()

비동기 함수, 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)

4-2. axios library 활용

하위호환성이 좋다.

axios({
  url: 'https://www.omdbapi.com?apikey=7035c60c&s=frozen',
  method: 'GET'
})
.then(res => console.log(res));

console.log(123)

4-3. async await

같이 세트로 묶어서 사용해야 한다. 비동기 함수임을 선언한다. 동기처럼 처리할 수 있게 만들어 준다.

// 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);
  }) 
};
profile
잘 할 수 있는 개발자가 되기 위하여

0개의 댓글