js 기본기 연습

미마모코딩·2022년 12월 1일
0

기본기연습

목록 보기
1/2
post-thumbnail

오늘은 간만에 배열접근 , 객체접근의 대한 정확도와 속도를 스스로 체크하기 위해 기본기연습을 하려하고있다.

배열접근은 먼저

<script>
const array = [1, 23, 5, [11, 3, 2, 27, [333, [1]]]];
</script>

위 배열의 333의 값을 666으로 바꾸려면?

<script>
 const array = [1, 23, 5, [11, 3, 2, 27, [333, [1]]]];
  array[3][4][0] = 6666;
  console.log(array[3][4][0]);
  </script>

위와같은 방법으로 할 수 있겠다.

<script>
const array: any = [1, 23, 5, [11, 3, 2, 27, [333, [1]]]];
  array[3][4][0] = 6666;
  const array2 = [3, 5, 6, 7, [111, 2], [0, [777]]];
  const array3 = array.concat(array2);
  console.log(array3);//(10) [1, 23, 5, Array(5), 3, 5, 6, 7, Array(2), Array(2)]
  
</script>

concat을 이용해 배열을 합쳐주었고 array3에서의 777의 값을 999로 바꾸어보자.

<script>
const array: any = [1, 23, 5, [11, 3, 2, 27, [333, [1]]]];
  array[3][4][0] = 6666;
  const array2 = [3, 5, 6, 7, [111, 2], [0, [777]]];
  const array3 = array.concat(array2);
  array3[9][1] = 999;
  console.log(array3);
 </script>

위와같은 방법으로 접근해서 데이터를 가져올 수 있다.

이번엔 객체를 복습해보자.

<script>
 const coffee = [
    {
      location: "인천 검암로 ",
      kinds: [
        {
          name: "바닐라라떼",
          price: 3000,
        },
        {
          name: "아메리카노",
          price: 2000,
        },
        {
          name: "에스프레소",
          price: 2500,
        },
      ],
    },
  ];
</script>

위와같은 구조에서 아메리카노의 가격을 2500으로 바꾸어보자.

coffee[0].kinds[1].price = 2500;
coffee[0].kinds[1]["price"] = 24500;
하지만 위와같은 방식은 가독성이 떨어진다.

이렇게 개선해보자.

const americano = coffee[0].kinds[1]
americano.price = 2400 

위와같이 개선하면 훨씬 가독성 좋게 할 수 있다.


위와같이 할 수 있을 것이다.
위에 ["price"]는 대괄호표기법으로 프로퍼티의 키로 접근해 벨류를 24500으로 바꾼것이다.

그럼 새로운 프로퍼티를 만들어보자

<script>
const mocha = {
name:"모카라떼",
price:4000
}
coffee[0].kinds.push(mocha)
</script>

위와같이 추가 할 수 있을 것이다.

다음엔 리팩토링에 대해서 포스팅 해볼것이다

0개의 댓글