[section6:배열 다루기] 클린 코드 자바스크립트

김보나·2022년 9월 14일
0

javascript

목록 보기
9/12
post-thumbnail

오랜만에 남아있는 강의를 들으려고 유데미를 켰다. 오늘 배울 부분은 배열 다루기!


js의 배열은 객체다.

  1. 배열에 어떤 값을 집어 넣어도 들어감(값,배열,객체,함수...)
  2. 객체와 유사하게 배열이 구성되는 모습을 볼 수 있음.
  3. typeof 연산자나, length연산자로 배열을 판단할 경우 오류가 생기는 경우가 있음(객체 처럼 취급되기도 하고, string도 length를 사용할 수 있기 때문!)
    => 따라서 배열을 검사할 때는
    Array.isArray(arr)
    을 사용해서 검사하는게 바람직하다.

Array.length

1.length를 통해 배열이 바뀔 수 있음


const arr = [1,2,3];
arr[3]=4
console.log(arr.length); //4

arr[9]=10;
console.log(arr)//[1,2,3,4, , , , , , 10]

위와 같은 형식으로 배열이 바뀔 수 있다!

  1. length를 통해 배열 초기화하기
    array.length =0을 통해 배열을 초기화 할 수 있다.

=> length를 통해 배열이 바뀔 수 있다는것을 의식하고 사용하자!

배열 요소에 접근하기

  • 배열에서 [0],[1] 등 인덱스로 접근하는걸 제한하는게 좋다. 왜냐면 배열은 객체처럼 사용될 수 있기 때문! 그리고 가독성도 떨어진다.

  • 구조 분해 할당을 통해 배열을 분해하자!

예시 1. 함수 인자로 배열을 받을 때 바로 구조 분해 할당으로 받기


//원래 코드
function operateTime(input,operators,is)
{
inputs[0].split('').forEach((num)=>                            {~~~~}
inputs[1].split('').forEach((num)=>                            {~~~~}
	}

//인덱스로 요소를 가져오지 말자!
function operateTime(input,operators,is)
{
  const [firstInput,secondInput] = inputs
firstInput.split('').forEach((num)=>                            {~~~~}
secondInput.split('').forEach((num)=>                            {~~~~}
	}


//파라미터로 받을 때 부터 구조분해 할당을 해버리자
function operateTime([firstInput,secondInput] ,operators,is)
{

firstInput.split('').forEach((num)=>                            {~~~~}
secondInput.split('').forEach((num)=>                            {~~~~}
	}
                              

예시 2. html요소 접근할 때

//원래 코드
function clickGroupButton(){
const confirmButton = document.getElementByTagName('button')[0];
const cancelButton = document.getElementByTagName('button')[1];
const resetButton = document.getElementByTagName('button')[2];
}

//클린코드
const [confirmButton,cancelButton, resetButton] = document.getElementByTagName('button')


  • getElementByTagName : 태그 이름으로 요소를 가져오는것. 배열로 가져오고 *을 통해모든 태그에 접근도 가능하다.

예시3. 하나만 사용할 때도 구조분해 할당 하기!


//기존에 사용했던 코드
const date = targetDate.toISOString().split('T')[0];

//구조분해할당으로 바꾸기
const [date] = targetDate.toISOString().split('T');

유사 배열, 객체

  • 객체에는 고차함수가 존재하지 않는데,
    객체는 배열로 바꾸기가 쉽다.
    객체를 탐색할 때는 배열로 바꿔서 탐색할 것!

const arguments  = {0:1,1:2,2:3}

Array.from(arguments);

불변성

  1. 원래 배열을 새로운 배열에 할당하면 둘 다 바뀜 ( const newArray = arr)
  2. 배열을 복사해서 사용하거나 새로운 배열을 반환하는 메서드를 사용하기!(map,filter,slice .... )
const numbers = [1,2,3]
const numbersCopy = [...numbers];

매소드 체이닝

  • 고차함수를 여러번 쓸 때는 아래와 같이 쓰면 좋다.
function getWonPrice(priceList){
return priceList
  .filter(isOverOneThousand)
  .sort(ascendingList)
  .map(suffixWon);
}
  • 고차함수 안에 들어가는 함수도 선언해서 사용하는게 가독성이 더 좋은듯!

forEach VS Map

  1. forEach : 요소마다 함수만 실행, 반환값은 undefined.
    -> 리턴이 필요 없을 때 사용
  2. map : 요소마다 함수를 실행해서 새로운 배열 반환
    -> 리턴이 필요할 때 사용

break, continue

  • 고차함수에서는 continue, break 등 사용 불가
  • try-catch를 사용하거나 아래와 같은 함수를 사용하기
  • for of
	    const array1 = ['a', 'b', 'c'];

for (const element of array1) {
  console.log(element);
}

// expected output: "a"
// expected output: "b"
// expected output: "c"
  • for in
	    for (const variable in object) {
      statement
    }

/*
variable
매번 반복마다 다른 속성이름(Value name)이 변수(variable)로 지정됩니다.

object
반복작업을 수행할 객체로 열거형 속성을 가지고 있는 객체
*/
  1. some : 배열 안에 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트 (빈 배열일 때는 false반환)
const array = [1, 2, 3, 4, 5];

// checks whether an element is even
const even = (element) => element % 2 === 0;

console.log(array.some(even));
// expected output: true

2.find : 주어진 판별 함수를 만족하는 첫번째 요소의 값을 반환함. 없으면 undefind 반환

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

3.every : 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트. boolean 값 반환

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));
// expected output: true

4.findIndex : 주어진 판별 함수를 만족하는 배열의 첫번째 요소에 대한 인덱스 반환, 없으면 -1 리턴

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

코테 준비겸 오랜만에 강의 남은 부분을 들었는데, 그동안 코딩하면서 이건가? 저건가? 이렇게 해도되나? 하는 부분에 대한 해답을 들을 수 있었다 !! 클린코드 넘 조항,,,
남은 강의들도 부지런히 들어야디

profile
우주최강 개발자가 될 때까지😈

0개의 댓글