본문 바로가기
  • soldonii's devlog
Javascript 공부/코드스테이츠(-)

코드스테이츠 프리코스 2주차 후기(2)

by soldonii 2019. 8. 26.

*코드스테이츠 프리코스 33기를 수강하면서 2019년 5월 9일(목)에 학습한 내용을 정리한 포스팅입니다.

*https://soldonii.github.io에서 작성한 글을 티스토리로 옮겨온 포스팅입니다.

*자바스크립트를 배우는 단계라 오류가 있을 수 있습니다. 틀린 내용은 댓글로 말씀해주시면 수정하겠습니다. 감사합니다. :)


1. 배열 다루기(Array Method)

코드 스테이츠 Pre course 33기 2주차 목요일(2019-05-09)에는 배열 다루기에 대해서 배웠다. 이런 method들은 MDN에서 사용법을 검색하면 되지만, 자주 쓰는 method에 대한 개인 학습 차원에서 상세하게 정리해보려 한다.

  • Array.isArray() : 검사할 대상이 배열인지 확인해주는 method이다.(typeof는 array와 object를 구분해서 알려주지 않고 둘 다 "object"라고 알려준다.
let arr = [a, b, c];
let obj = {
 name : 'hyunsol',
 age : 29
};
Array.isArray(arr); // true
Array.isArray(obj); // false

 

  • arr.push(newElement) : 배열에 element를 추가한다. element가 추가됐을 때 해당 배열의 길이를 return한다. MUTABLE
let fruits = ['apple', 'grape', 'watermelon'];
fruits.push('banana', 'strawberry'); // 5('banana', 'strawberry'가 추가된 fruits 배열의 길이를 return)
console.log(fruits) // ['apple', 'grape', 'watermelon', 'banana', 'strawberry'] 원본이 변화된 것을 볼 수 있다.(MUTABLE)

 

  • arr.pop() : 배열의 뒤에서부터 element를 제거한다. 제거된 element를 return한다. MUTABLE
let numbers = [23, 11, 383, 2910];
numbers.pop(); // 2910(제거된 element를 return)
console.log(numbers); // [23, 11, 383] 원본이 변화된 것을 볼 수 있다.(MUTABLE)

 

  • arr.splice(start[, deleteCount[, item1[, item2[,...]]]]) : 배열에서 특정 위치에 있는 값을 제거하고, 그 자리에 새로운 값을 추가할 때 사용한다.MUTABLE
let brands = ['liful', 'thisisneverthat', 'brownbreath', 'newbalance', 'blankof'];
brands.splice(2, 1, 'neithers', 'heritagefloss'); // 'brownbreath'(제거된 element를 return)
console.log(brands); // ['liful', 'thisisneverthat', 'neithers', 'heritagefloss', 'newbalance', 'blankof'] 원본이 변화된 것을 볼 수 있다.(MUTABLE)

 

  • arr.slice([begin[, end]]) : begin index ~ end-1 index에 해당되는 새로운 배열을 return한다. 하나의 배열을 복사(shallow copy)할 때 유용하다. IMMUTABLE
let device = ['iphone', 'macbook', 'ipad', 'airpod', 'apple watch', 'ipod'];
let newDevice1 = device.slice(); // ['iphone', 'macbook', 'ipad', 'airpod', 'apple watch', 'ipod']
let newDevice2 = device.slice(0, 3); // ['iphone', 'macbook', 'ipad'] 0번째~2번째 index 값이 새로운 배열이 되었다.
let newDevice3 = device.slice(3, 100); // ['airpod', 'apple watch', 'ipod']

 

  • arr.join([separator]) : 구분자에 맞춰 배열을 문자열로 변환해준다.(⟷ str.split()은 문자열을 배열로 전환) IMMUTABLE
let clothes = ['shirts', 'pants', 't-shirts', 'innerwear'];
let clothesStr = clothes.join(); // "shirts,pants,t-shirts,innerwear"(자동으로 ,로 분류됨)
let clothesStr2 = clothes.join(' '); // "shirts pants t-shirts innerwear"
let clothesStr3 = clothes.join(' / '); // "shirts / pants / t-shirts / innerwear"

 

  • arr.indexOf(searchValue) : str.indexOf()와 같은 method. 배열 내에 searchValue가 존재하면 해당 index를 return, 발견되지 않으면 -1을 return한다. 마찬가지로 true/false가 return되길 원할 경우 includes method를 활용한다. IMMUTABLE
let arr = ['hyunsol', 'soldonii', 'do', 29];
arr.indexOf(29); // 3
arr.indexOf('hyunsol'); // 0
arr.indexOf('Soldonii') // -1 (대소문자 구별)

아래는 callback 함수와 관련된 method를 살펴볼 예정이다. 내가 아직 이 callback 함수들에 대해서 100% 이해했는지 모르겠어서, 해당 method들만 따로 모아 놓았다.

 

Callback이란?
- 쉽게 말하면, '어떠한 함수의 인자(argument)가 함수인 경우'를 의미한다.
- javascript에서 함수는 하나의 값이다. 그렇기 때문에 다른 함수의 인자로 함수가 전달될 수 있다.
- callback 함수를 사용하여, original 함수의 동작방법을 변형할 수 있다.

여태까지 내가 문제를 풀면서 생성했던 함수들은 인자(argument)로 모두 변수나 숫자형, 문자형 데이터 타입 같은 간단한 형태만 인자로 받았었다. 그러나 함수 또한 자바스크립트에서는 하나의 '값'이기 때문에 함수 또한 다른 함수의 인자로 수신될 수 있는 것이다. callback 함수 관련 method 사례를 통해 이해해보자.

  • arr.forEach(callback) : 반복문에서 배웠던 for문이 하는 일을 대체할 수 있는 method이다. 즉, forEach()의 괄호 안에 parameter로 받게되는 함수를 반복실행시키는 함수이다. IMMUTABLE
    • arr.forEach(callback(element[, index[, array]])[, thisArg]);
// 1. 반복적으로 실행하고 싶은 함수를 생성한다.(이 함수가 callback 함수가 된다.)
function printArray(currentElement, index, array) {
  console.log(`${index}: ${currentElement}`); // 배열 내 각 index의 값을 출력하는 함수를 생성했다.
}
['hello', 3, 5].forEach(printArray);
// ['hello', 3, 5] 배열에서 forEach 메소드를 실행했다. argument로 printArray 함수가 들어왔고, 
// 이 함수는 배열 내 각 index의 값을 출력하는 함수이다. forEach에 의해 이 배열이 끝날 때까지 printArray가 실행
// 0: 'hello'
// 1: 3
// 2: 5

 

  • arr.map(callback) : callback이 실행되며 return되는 값들을 모은 새로운 배열을 만들 때 사용한다. (기존 배열과 길이는 같지만, element가 다른 새로운 배열을 만들 때 유용하다고 한다.) IMMUTABLE
    • arr.map(callback(element[, index[, array]])[, thisArg]);
// 배열 내 객체의 값들을, 새롭게 바꾸어보자.
let arr = [{key : 1, value : 10}, 
           {key : 2, value : 322},
           {key : 3, value : 955}] // 배열 내 객체를 가지고 있는 배열을 만들었다.
function changeArr(obj) {
  let newObj = {};
  newObj[obj.key] = obj.value;
  return newObj; 
} // 객체를 parameter로 받고, 해당 객체의 key와 value를 받는 새로운 객체를 만든다.
arr.map(changeArr); // map 메소드를 통해 changeArr 콜백함수를 실행하여 새로운 배열을 만든다.
// [{1:10}, {2:322}, {3:955}]

 

  • arr.fliter(callback) : boolean 형태의 return을 callback 내에서 반환받은 후, 조건을 통과한(true) element만 담은 새로운 배열을 만든다. IMMUTABLE
    • arr.filter(callback(element[, index[, array]])[, thisArg]);
function isBigEnough(value) {
  return value >= 10;
}
let filtered = [1, 3, 57, 12, 8].filter(isBigEnough); // [57, 12]

 

  • arr.reduce(callback) :
    • arr.reduce(callback(accumulator, currentValue[, currentIndex[,array]])[, initialValue])
    • 기본적으로 배열의 합을 구할 수 있다는 건 알겠는데, mdn을 보면 정말 다양한 예제들이 있는데 내가 아직 명확히 다 이해를 못해서 여기에 예제를 옮겨적는 대신 mdn 링크를 걸어두는 것으로 우선 이 내용은 대체하겠다.
    • arr.reduce 관련 MDN 문서

댓글