Array.prototype 추가된 문법
toSorted()
sort()메서드는 불변성을 유지시키지 못하지만 toSorted()메서드는 원본배열과 다른 배열을 뱉어주기때문에 불변성을 유지시켜 줄 수 있다.
const originSorted = [1,2,3,4,5];
const newSorted = originSorted.sort((a,b)=> b-a);
console.log(originSorted);//[5,4,3,2,1]
console.log(newSorted);//[5,4,3,2,1]
console.log(originSorted === newSorted);//true
const originToSorted = [1,2,3,4,5];
const newToSorted = originToSorted.toSorted((a,b)=> b-a);
console.log(originToSorted);//[1,2,3,4,5]
console.log(newToSorted);//[5,4,3,2,1]
console.log(originToSorted === newToSorted);//false
JavaScript
복사
toReverse()
reverse()메서드도 마찬가지로 불변성을 유지시키지 못하지만 toReverse()메서드는 원본배열과 다른 배열을 뱉어주기때문에 불변성을 유지시켜 줄 수 있다.
const originReverse = [1,2,3,4,5];
const newReverse = originReverse.reverse();
console.log(originReverse);//[5,4,3,2,1];
console.log(newReverse);//[5,4,3,2,1]
console.log(originReverse === newReverse);//true
const originReverse = [1,2,3,4,5];
const newReverse = originReverse.toReverse();
console.log(originReverse);//[1,2,3,4,5]
console.log(newReverse);//[5,4,3,2,1]
console.log(originReverse === newReverse);//false
원본배열과 다른 배열을 뱉어준다.
JavaScript
복사
with(index, value)
with 객체안에서 index번째 값을 value로 바꿔준다.
const originWith = [1,2,3,4,5];
const newWith = originWith.with(3,100);
console.log(originWith);//[1,2,3,4,5]
console.log(newWith);//[1,2,3,100,5]
console.log(originWith === newWith);//false
JavaScript
복사
with()메서드는 첫번째 인자값으로 인덱스를 받고 두번째 인자값으로 대체할 값을 받는다.
with(3,10)을 해석하자면 배열의 3번째 인덱스 값을 100으로 바꿔줘! 라는 뜻이다.
기존에는 slice를 사용하여 코드가독성이 떨어지는 측면이 있었는데 이를 해결해 준 느낌이다.
ex) [...array.slice(0,3), 바꿔줄 값, ...array.slice(4)]
findLast()
find()메서드는 앞에서부터 탐색을 하고 findLast는 뒤에서부터 탐색을 시작한다.
const find = [1,2,3,4,5];
find.find((el) => console.log(el));//1,2,3,4,5
const findLast = [1,2,3,4,5];
findLast.findLast((el) => console.log(el))//5,4,3,2,1
JavaScript
복사
findLastIndex()
findIndex메서드는 앞에서부 탐색을 하고 findLastIndex메서드는 뒤에서부터 탐색을 시작한다.
const findIndex = [1,2,3,4,5];
findIndex.findIndex((_,idx) => console.log(idx))//0,1,2,3,4
const findLastIndex = [1,2,3,4,5];
findLastIndex.findLastIndex((_,idx) => console.log(idx))//4,3,2,1,0
JavaScript
복사