본문 바로가기

Study/JS

JS - 배열 순서 바꾸기

 1. 배열의 마지막 요소를 맨 앞으로 이동하기

let fruits = ["grape", "orange", "peer", "apple"];
let last = fruits[fruits.length-1];

fruits.splice(fruits.length-1, 1);
fruits.unshift(last)

console.log( fruits ); // ['apple', 'grape', 'orange', 'peer']

 

 2. 요소 맞교환하기

let fruits = ["grape", "orange", "peer", "apple"];
let tmp = fruits[3];

fruits[3] = fruits[0];
fruits[0] = tmp;

console.log(fruits) // ['apple', 'orange', 'peer', 'grape']
 
 

'Study > JS' 카테고리의 다른 글

JS - 문자열에서 숫자 추출하기  (0) 2023.02.28
JS - Array.prototype.map() 구현하기  (0) 2022.11.02
JS - Array.prototype.filter() 구현하기  (0) 2022.11.02
JS - Array.prototype.reduce() 구현하기  (0) 2022.11.02
클로저 (Closure)  (0) 2022.10.05