Sharryhong's Front-End
  • About Sharryhong's Front-End Blog.
  • Front-End Dev
    • Flutter
      • API Key 안전하게 숨기기. Cloudflare Workers!
      • Web CORS 에러
    • Vue.js
      • usePagination - composition api (vue2)
      • Pagination Component
      • Vue Image Skeleton
      • Sort an Array of Objects by Boolean property
      • Dynamic Components
      • LoadingBar Component
      • composition-api 사용하여 menu 의 outside click 시 close
      • vue+TypeScript
      • Vue.js 개발자를 위한 VS Code
      • Vue3 Chrome Extension
      • input file 선택된 파일 명 reset하기
      • element 내부 scroll 될 때, ScrollTop 값에 따라 div를 보이게, 안보이게 제어하기
      • 진입한 url path에 맞게 메서드 실행
    • React
      • 절대경로(absolute path) 설정, jsx파일로 이동 설정
      • useContext rerender issue
      • Firebase v9 Auth with React
      • Firebase v9 Realtime Database with React
      • React Star Rating (별점 표시)
      • React App deploying (배포)
    • Next.js
      • CSR, SSR, Next.js
    • API Mocking
      • Vue 에서 msw 적용하기
    • Storybook
      • styled-component theme.ts가 storybook엔 적용안되는 이슈
      • storybook에서 alias path 안되는 이슈
      • storybook에 Global Style 적용하기
  • etc
    • brew update
    • npm upgrade (mac)
  • DEV BETTER
    • Clean Code
      • Clean Code JavaScript 강의
        • Variables - 변수 다루기
        • Boundary - 경계 다루기
        • Conditional - 분기 다루기
        • Array - 배열 다루기
      • Tip. 클린 코드를 위한 5가지 팁
      • Tip. 코딩 잘하는 팁 3가지
    • 웹 성능 최적화 (performance)
      • performance 강의
        • loading, rendering performance
        • Tools
        • Image size optimization
        • bottleneck (병목) code 탐색
Powered by GitBook
On this page
  • JS의 배열은 객체이다.
  • Array.length
  • 배열 요소에 접근하기
  • 유사 배열 객체
  • 불변성 (immutable)
  • for문 배열 고차함수로 리팩토링
  • 배열 메서드 체이닝 활용하기
  • map vs forEach

Was this helpful?

  1. DEV BETTER
  2. Clean Code
  3. Clean Code JavaScript 강의

Array - 배열 다루기

2022-01

JS의 배열은 객체이다.

배열은 객체이므로 주의가 많이 필요하다.

배열임을 확인하고 싶을때는 Array.isArray(arr); 를 활용하자.

Array.length

length는 배열의 길이보다는, 배열의 마지막 index라고 생각하자.

arr.length = 0; 으로 하면 배열이 초기화된다.

주의해서 사용하자.

배열 요소에 접근하기

[0], [1] 으로 요소에 접근하는 코드를 지양하자.

input[0], input[1] 의 경우

개선코드 예 1)

const [firstInput, secondInput] = input; 

개선코드 예2) 함수에서 받을 때부터 분해하기

function operateTime([firstInput, secondInput].. ) { 
  ... 
} 

operateTime([1, 2],...) 

개선코드 예3) 유틸함수 만들어 사용하기. lodash의 _.head(array) // 첫번째 요소 얻기

function head(arr) {
  return arr[0] ?? '없을때처리'
}

function formatDate(targetData) {
  const date = head(targetDate.toISOString().split('T'));
  const [year, month, day] = date.split('-');

  return `${year}년  ${month}월 ${day}일`;
}

유사 배열 객체

예 : 함수 내에서 사용하는 arguments, querySelectAll 엘리먼트 리스트

진짜 배열이 아니기때문에 내부 프로토타입에 배열 내장함수가 없다.

배열로 바꿔준 후 사용한다.

Array.from(arguments).map((arg) => ...)

불변성 (immutable)

원본배열의 불변성을 지키기 위해서는

방법 1. 배열을 복사한다.

function copyArray(originArray) {
  const newArray = [ ...originArray ];
  return newArray;
}

방법 2. 새로운 배열을 반환하는 메서드들을 활용한다.

filter(), map(), slice() 등 

push, unshift등의 함수는 원본 배열을 바꾼다.

for문 배열 고차함수로 리팩토링

임시변수 사용코드

const price = [1000,2000,3000];

function getWonPrice(priceList) {
  let temp = [];
  for (let i = 0; i < priceList.length; i++) {
    temp.push(priceList[i] + '원');
  }
  return temp;
}

map 배열 고차함수를 이용해서 선언, 명시적으로 리팩토링

const price = [1000,2000,3000];

function getWonPrice(priceList) {
  return priceList.map((price) => price + '원');
}

배열 메서드 체이닝 활용하기

체이닝 활용 전 코드

const price = [5000,2000,1000,3000,1500];

const suffixWon = (price) => price + '원';
const isOverOneThousand = (price) => price > 1000;
const ascendingList = (a, b) => a - b;

function getWonPrice(priceList) {
  const isOverList = priceList.filter(isOverOneThousand);
  const sortList = isOverList.sort(ascendingList);
  
  return isOverList.map(suffixWon)
}

메서드 체이닝 활용 : 명시적, 앞으로 계속 코드가 추가되어도 명확하게 작성할 수 있다.

const price = [5000,2000,1000,3000,1500];

const suffixWon = (price) => price + '원';
const isOverOneThousand = (price) => price > 1000;
const ascendingList = (a, b) => a - b;

function getWonPrice(priceList) {
  return priceList
    .filter(isOverOneThousand)
    .sort(ascendingList)
    .map(suffixWon);
}

map vs forEach

forEach는 매 요소마다 함수를 실행한다.

map은 매 요소마다 함수를 실행하고 결과값을 저장해 새로운 배열을 반환한다.

즉,

반환값 없이 배열 요소를 순환하면서 함수 실행만 할 경우는 forEach 사용

새로운 배열을 만들때는 map을 사용한다.

PreviousConditional - 분기 다루기NextTip. 클린 코드를 위한 5가지 팁

Last updated 3 years ago

Was this helpful?