[TIL] JS: 드림코딩 강의노트 04

송나은·2021년 2월 14일
0

JavaScript

목록 보기
15/23

자료구조

동일한 type의 object를 모아 놓은 것

  • object 서로 연관된 특징과 행동 등을 묶어 놓은 것
  • array 칸칸이 모여있는 자료구조

Array

  • 배열을 선언하는 방법
  1. object와 같은 방법으로 const arr1 = new Array()
  2. 대괄호 이용 const arr2 = [1, 2]
  • Index
    대괄호를 이용하여 데이터를 검색하고 삽입, 삭제할 수 있다.

    첫 번째 아이템은 Array[0], 마지막 아이템은 Array[Array.length -1]

Array APIs

⭐ VScode에서 Ctrl을 눌러 내장함수의 API를 확인할 수 있다. ⭐

  • forEach 배열에 들어있는 값마다 콜백함수를 수행한다.
  • unshift / push 데이터 삽입
  • shift / pop 데이터 삭제

    배열의 길이가 길 수록 pop / push를 사용하는 게 좋다. unshift / shift는 앞에서부터 실행되기 때문에 배열이 움직이는 시간이 오래 걸린다.

  • splice(start: number) 배열 자체에서 인덱스 번호와 개수를 입력하여 제거하거나 대체 할 수 있다.
    Array.splice(1, 1, 'a','b') Index 1에서 하나의 아이템을 지우고 a, b 를 추가한다.
  • slice(start: number, end: number) 배열에서 원하는 부분만 반환하여 가져온다.
  • concat 배열을 합하여 새로운 배열을 return하는 방법.
    const newArray = Array.concat(Array2)
  • indexOf / lastIndexOf 아이템의 위치(Index값)를 검색하는 방법.

    아이템의 Index배열 안에 해당하는 값이 없을 때에는 -1이 출력된다.

  • includes 아이템이 있는지 없는지 true / false 로 출력한다.
  • join('구분자') 배열을 string으로 가져오는 방법. 구분자를 입력하지 않으면 콤마로 반환된다.
  • split('구분자') String을 배열로 만드는 방법.
  • reverse 배열안의 아이템 순서 거꾸로 바꾸어 반환한다.

Quiz 풀어보기

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const student = [
  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),
  ];
  • find 콜백함수를 만들어 전달한 값이 True일 때 값이 반환된다.
// 90점을 받은 학생 찾기
const result = student.find((student) => student.score === 90);
console.log(result); // Student {name: "C", age: 30, enrolled: true, score: 90}
  • filter 콜백함수를 만들어 값이 True인 값만 가져온다.
// 등록한 학생들 찾기
const result = student.filter((student) => student. enrolled);
console.log(result); // (3) [Student, Student, Student]
  • map 콜백함수를 만들어 배열에 있는 값을 변환하여 가져온다.
// 배열에서 점수만 가져오기
const result = student.map((student) => student.score);
console.log(result); // (5) [45, 80, 90, 66, 88]

// 50점 이상인 점수만 string으로 가져오기
const result = student
	.map((student) => student.score)
	.filter((score) => score >= 50)
	.join();
console.log(result); // 80, 90, 66, 88
  • sort 이전값과 현재값의 차가 마이너스 값일 때 오름차순, 플러스 값일 때 내림차순으로 정렬이 된다.
const result = students
	.map((student)=> student.score)
	.sort((a,b) => a-b)
	.join();
console.log(result); // 45, 66, 80, 88, 90
}
  • some 배열에서 하나라도 만족하는 값이 있으면 True로 return된다.
  • every 배열의 모든 값이 만족하면 True로 return 된다.
// 50점 이하의 학생이 있는지 없는지 확인하기
const result = student.some((student) => student.score < 50));
console.log(result); // true
  • reduce 원하는 시작점부터 배열의 값을 누적한다.
    -> prev은 이전의 콜백함수에서 리턴된 값, curr은 배열의 아이템을 순차적으로 전달 받는다.
// 점수의 평균 구하기
const result = student.reduce((prev, curr) => prev + curr.score, 0);
console.log(result / students.length); // 73.8

JSON

  1. 데이터를 주고 받을 때 쓸 수 있는 가장 간단한 데이터 포맷이다.
  2. 텍스트를 기반으로 하여 가볍고 읽기 편하다.
  3. key와 value로 이루어져 있다.
  4. 프로그램언어와 플랫폼에 상관없이 사용할 수 있다.
  • stringify
let json = JSON.stringify(['a','b']);
console.log(json); // ["a", "b"]

const rabbit ={
  name: 'tori'
  birthDate: new Date(),
  jump: () => {
    console.log(`${name} can jump!`);
  }
}

json = JSON.stringify(rabbit, ['name']);
console.log(json); // {"name":"tori"}

Object를 JSON으로 변환할 때, 함수와 JS에만 있는 dataType은 JSON에 포함되지 않는다.

  • parse
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);

console.log(rabbit.birthdate.getDate()); // 날짜를 가져온다
console.log(obj.birthDate.getDate()); // String 형태로 저장되었기 때문에 getDate() 함수가 실행되지 않는다.

Tip

profile
그때그때 공부한 내용과 생각을 기록하는 블로그입니다.

0개의 댓글