Programing/JavaScript

Javascript 배열 값에 접근하는 간결하고 가독성을 높이는 방법 at()

리커니 2022. 2. 24. 17:36
반응형

Javascript 배열 값에 접근하는 간결하고 가독성을 높이는 방법 at()

 

Javascript 에서 배열에 접근 할때는 대괄호와 index를 사용해서 접근 할 수 있습니다.

 

[대괄호 & 인덱스로 접근]

const array = [1,2,3,4,5];
const firstValue = array[0]; /*첫번째 값 반환(index 0)*/
const lastValue = array[array.length - 1]; /*마지막 값 반환(index 4)*/

 

Javascript 에서는 대괄호 표기법보다 간결하고 가독성을 높일 수 있는 at() 이라는 메서드를 제공합니다.

 

[at 문법]

array.at(index);

at 메서드에 파라메터로 index를 넘기면 해당 index의 값을 리턴해줍니다.

위의 대괄호 표기법과 같은 예제로 비교해 보도록 하죠.

 

[at 메서드로 접근]

const array = [1,2,3,4,5];
const firstValue = array.at(0); /*첫번째 값 반환(index 0)*/
const lastValue = array.at(-1); /*마지막 값 반환(index 4)*/

 

위에서 보시는 것 처럼 음수로 인덱스를 넘기게 되면 뒤에서부터 접근을 합니다.

대괄호 표기법보다 간결하게 접근 할 수 있죠.

 

[마지막 index에 접근]

/*마지막 값에 접근하는 방법 비교*/
array[array.length - 1];
array.at(-1);

 

두 방법 모두 존재하지 않는 index로 접근하면 undefined를 리턴합니다.

 

[존재하지 않는 index 접근]

const array = [1,2,3,4,5];
console.log(array[5]);  /* undefined */
console.log(array.at(5); /* undefined */

 

at 메서드는 HTMLCollection, NodeList와 같은 유사배열에는 제공되지 않으니 주의하세요.

 

[오직 배열 객체에만 사용에 주의]

<div id="test">
    <span>1</span>
    <span>2</span>
</div>

<script>
const div = document.getElementById("test");
console.log(test.children[0]); /*<span>1</span>*/
console.log(test.childNodes[3]); /*<span>2</span>*/
console.log(test.children.at(0)); /*test.children.at is not a function*/
</script>

 

IE와 Opera Android 에서는 at 메서드가 제공되지 않으니 주의하세요.

 

★값에 접근에만 사용하고 undefined인 값을 생성하는데는 사용하지 않습니다.

 

[오직 접근에만 사용]

const array = [[1,2,3,4,5]];
array.at(1) = [1,2,3,4,5]; //Uncaught ReferenceError: Invalid left-hand side in assignment
array[1] = [1,2,3,4,5]; //정상 동작

 

반응형