-
Array.prototype.at으로 마지막 배열 값 쉽게 구하기Javascript 2023. 7. 13. 11:32
at은 비교적 최근에 추가 된 Array의 메서드다. 배열에서 해당하는 인덱스의 값을 반환해 준다. 대괄호 표기법(array[1])과 무엇이 다르냐 할 수 있는데,at메서드의 강점은 음수를 넘겨줄 경우 배열의 뒤에서 부터 인덱스를 구한다는 것이다.const animals = ['cat', 'dog', 'cow']; console.log(animals[0]); // 'cat' console.log(animals.at(0)); // 'cat' console.log(animals[-1]); // undefined console.log(animals.at(-1)); // 'cow' // 배열에 없는 인덱스일 경우 undefined를 리턴한다. console.log(animals.at(3)); // undefined방법 비교
아래 코드는 모두 마지막 배열의 값을 구해오지만, at을 사용한 코드가 가장 간결하다.
const colors = ['red', 'blue', 'orange']; // #1 length를 사용 const useLength = colors[colors.length - 1]; // length는 배열의 요소 '갯수'를 구해오고, 실제 인덱스는 0부터 시작하니 -1을 해줘야 한다. console.log(useLength); // 'orange' // #2 slice를 사용 // slice는 배열의 요소가 아닌 '배열'을 반환하니 주의한다. const useSlice = colors.slice(-1); console.log(useSlice); // ['orange'] // #3 at을 사용 const useAt = colors.at(-1); console.log(useAt); // 'orange'요소가 객체일 경우 주의할 점
at으로 구해오는 배열의 객체 요소도 다른 방법으로 가져온 것 처럼 얕은 복사(shallow copy)되므로 주의해야 한다.
const cats = [ { name: 'blanc', age: 4, }, { name: 'aranc', age: 3, }, ]; const lastCat = cats.at(-1); console.log(lastCat); // {name: "aranc", age: 3} lastCat.age = 5; console.log(lastCat); // {name: "aranc", age: 5} console.log(cats[1]); // {name: "aranc", age: 5}