js 배열 스왑할때

낭만개발자·2022년 9월 7일
0

알고리즘

목록 보기
17/20

기본: temp 변수 사용

let arr = [1,2,3,4,5];

//arr[0], arr[2] swap
let temp = arr[0];
arr[0] = arr[2];
arr[2] = temp;
console.log(arr);
// [3,2,1,4,5]

구조 분해 할당 사용

let arr = [1,2,3,4,5];

//arr[0], arr[2] swap

[arr[2], arr[0]] = [arr[0], arr[2]];

console.log(arr);
// [3,2,1,4,5]

2개 뿐 아니라 n개 가능

출 : https://miiingo.tistory.com/364

profile
낭만닥터와 슬의를 보고 저런 개발자가 되어야 겠다고 꿈꿔봅니다.

0개의 댓글