갈푸라떼
갈푸라떼는 개발중
갈푸라떼
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • CS (0)
      • CSinfo (0)
    • Frontend (15)
      • HTML,CSS (1)
      • Javascript (2)
      • React (0)
      • React Hook (12)
    • Backend (0)
      • Python (0)
      • Node.js (0)
      • php (0)
    • DB (2)
      • MySQL (2)
      • BigQuery (0)
      • Mongodb (0)
    • Study (186)
      • JavaScript (72)
      • JavaScript(Clean code) (50)
      • Node.js (11)
      • HTML,CSS (13)
      • React (30)
      • TypeScript (10)
      • React-Native (0)
    • Error (2)
      • error (2)
    • Git (22)
      • Git (22)
    • Help Coding (4)
      • Useful websites (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github

공지사항

인기 글

태그

  • PM2
  • 객체타입
  • 인터프리터
  • this
  • class
  • 자바스크립트엔진
  • 스코프 체인
  • 실행 컨텍스트
  • Babel
  • structure
  • ECMAScript
  • 프로토타입
  • 함수
  • 오버라이딩
  • Arrow
  • symbol
  • 원시타입
  • SPREAD
  • 심볼
  • 호이스팅
  • 상속
  • 렉시컬 환경
  • 네이밍
  • 컴파일러
  • function
  • 싱글스레드
  • 정적 레벨
  • 이터러블
  • nodemon
  • prototype

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갈푸라떼

갈푸라떼는 개발중

Study/JavaScript(Clean code)

[JavaScript][clean-code] 배열 요소에 접근하기(구조 분해 할당)

2022. 6. 1. 16:48

* 배열 요소에 접근하기

- 배열에 있는 하나하나의 단위들을 요소라고 한다.

 

* 배열 요소 접근 예시

const array = [1, 2, 3]


function operateTime(input, operators, is) {
  inputs[0].split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });

  inputs[1].split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });
}
  • 배열의 요소를 index번호 [0], [1]으로 출력을 하고있어서 어떤요소가 담겨있는지 예측이 되지 않는다.
  • 가독성이 떨어진다.
  • 배열 요소에 좀 더 명확하게 접근할 필요성이 있다.

* 구조 분해 할당을 이용한 요소 접근

function operateTime(input, operators, is) {
  const [firstInput, secondInput] = input

  firstInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });

  secondInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });
}

* 매개변수에 배열을 넣어버리기

function operateTime([firstInput, secondInput], operators, is) {
  fitstInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });

  secondInput.split('').forEach((num) => {
    cy.get('.digit').contains(num).click();
  });
}

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

* 두번째 예시

function clickGroupButton() {
  const confirmButton = document.getElementsByTagName('button')[0];
  const cancelButton = document.getElementsByTagName('button')[1];
  const resetButton = document.getElementsByTagName('button')[2];

  // ... some code
}
function clickGroupButton() {
  const [confirmButton, cancelButton, resetButton] = document.getElementsByTagName('button');
  // ... some code
}
  • 구조 분해 할당을 이용해 축약
  • 역할에 대해서 굉장히 명시적이다.

* 세번째 예시

function formatData(targetDate) {
  const date = targetDate.toISOString().split('T')[0];

  const [year, month, day] = date.split('-');

  return `${year}년 ${month}월 ${day}일`;
}
function formatData(targetDate) {
  const [date] = targetDate.toISOString().split('T');

  const [year, month, day] = date.split('-');

  return `${year}년 ${month}월 ${day}일`;
}
  • 구조 분해 할당 사용
  • 하나를 분해 할 때도 사용할 수 있다.

* 구조분해할당이 불편하면 유틸함수를 만들면된다.

  • Lodash | _.head() Method 처럼 유틸 함수를 만든다.
  • _.head(array)
  • Gets the first element of array.
_.head([1, 2, 3]); // 1
_.head([]); // undefined

* 직접 유틸 함수를 만드는 예시

  • head라는 함수를 만든다. 인자로 받은 배열의 0번째 인덱스를 출력하고 빈값을 받으면 ' '를 반환한다.
  • nullish coalescing operator와 같이 사용
function head(arr) {
  return arr[0] ?? '';
}

function formatData(targetDate) {
  const date = head(targetDate.toISOString().split('T'))

  const [year, month, day] = date.split('-');

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

 

'Study > JavaScript(Clean code)' 카테고리의 다른 글

[JavaScript][clean-code] 불변성 (immutable)  (0) 2022.06.03
[JavaScript][clean-code] 유사 배열 객체  (0) 2022.06.03
[JavaScript][clean-code] Array.length  (0) 2022.06.01
[JavaScript][clean-code] JavaScript의 배열은 객체이다.  (0) 2022.06.01
[JavaScript][clean-code] 드 모르간의 법칙  (0) 2022.05.31
    'Study/JavaScript(Clean code)' 카테고리의 다른 글
    • [JavaScript][clean-code] 불변성 (immutable)
    • [JavaScript][clean-code] 유사 배열 객체
    • [JavaScript][clean-code] Array.length
    • [JavaScript][clean-code] JavaScript의 배열은 객체이다.
    갈푸라떼
    갈푸라떼

    티스토리툴바