[TIL] 자바스크립트 reverse() 함수

Mark·2022년 8월 10일
1
post-thumbnail

reverse()?

배열의 순서를 반대로 뒤집어 주는 함수, reverse() 함수를 사용하면 원본 자체가 변경되므로 주의해야 한다.


reverse() 구문

[배열].reverse()

반환 값

  • 순서가 반전된 배열

예제1) 기본 예제

const a = [1, 2, 3];
console.log(a); // [1, 2, 3]

a.reverse();
console.log(a); // [3, 2, 1]

예제2) 원본 배열은 그대로 유지하고 싶을 경우

전개 연산자

  • 객체나 배열을 담은 변수 앞에 ‘…’을 붙이면 된다.
// 원본 배열도 변경되는 경우 
const arr1 = [1,2,3]
const arr2 = arr1.reverse()

console.log(arr1); // [3, 2, 1]
console.log(arr2); // [3, 2, 1]

// 원본 배열은 유지하고 반전된 새로운 배열만 필요할 경우 -> 전개 연산자 활용
const arr1 = [1, 2, 3];
const arr2 = [...arr1].reverse();

console.log(arr1); // [1, 2, 3]
console.log(arr2); // [3, 2, 1] 

참고 자료

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

https://velog.io/@recordboy/전개-연산자Spread-Operator

https://ludeno-studying.tistory.com/70

profile
개인 공부 정리

0개의 댓글