배열의 두 요소 순서를 변경할 때

2023. 5. 5. 10:47·javascript

1. 임시 변수를 사용해서 변경한다.

// arr[0], arr[1] 변경해야하는 경우

const arr = [1, 2, 3, 4, 5];
let temp = arr[1];
arr[1] = arr[0];
arr[0] = temp;
// [2, 1, 3, 4, 5]

 

2. 구조분해 할당을 이용한다. 

const arr = [1, 2, 3, 4, 5];
[arr[0], arr[1]] = [arr[1], arr[0]];
// [2, 1, 3, 4, 5]

 

구조분해 할당을 이용하면 간단하게 순서를 변경할 수 있다. 

 

참고 

https://miiingo.tistory.com/364

'javascript' 카테고리의 다른 글

string 대문자, 소문자 체크하기  (0) 2023.05.05
String.charAt(index)  (0) 2023.05.05
Array.prototype.reduce()  (0) 2023.04.20
call, bind, apply의 this binding  (0) 2023.04.19
자바스크립트 sort()로직  (0) 2023.04.15
'javascript' 카테고리의 다른 글
  • string 대문자, 소문자 체크하기
  • String.charAt(index)
  • Array.prototype.reduce()
  • call, bind, apply의 this binding
ssund
ssund
  • ssund
    ssund의 기술블로그
    ssund
  • 전체
    오늘
    어제
    • TECH (82)
      • Next.js (8)
      • React (25)
      • Vite (1)
      • javascript (17)
      • CSS (6)
      • CS (10)
      • AWS (0)
      • Jest (1)
      • CI|CD (0)
      • 알고리즘 (8)
      • Tools (1)
      • Tips (5)
  • 블로그 메뉴

    • 링크

    • 공지사항

    • 인기 글

    • 태그

      react state management
      서버컴포넌트
      React
      git배포
      styled-components
      global-style
      reat-head
      타입스크립트
      call signatures
      웹브라우저구성
      Array.sort()
      커머스프로젝트
      TypeScript
      redux
      JavaScript
      app-router
      theme-provider
      함수와 메서드차이
      배열요소순서
      nextjs
    • 최근 댓글

    • 최근 글

    • hELLO· Designed By정상우.v4.10.0
    ssund
    배열의 두 요소 순서를 변경할 때
    상단으로

    티스토리툴바