이 기사에서는 배열 요소에 액세스할 때 Array.prototype.at()
가 Array[index]
보다 더 이상적인 이유를 살펴보겠습니다.
예전에는 배열 요소에 접근할 때 Array[index]
같은 Array[1]
을 사용하곤 했습니다. 이것이 제가 익숙한 것이며 배열 요소를 얻는 방법을 배운 방법입니다.
근데 동료가 최근 코드 리뷰에서 "색인을 직접 사용하는 대신 Array.prototype.at()
을 사용하면 어떨까요?"라고 물었습니다.
<code class="language-javascript">const element = arr[1];</code>그는 다음으로 변경할 것을 제안했습니다:
<code class="language-javascript">const element = arr.at(1);</code>이 접근 방식은 매우 간단하고 직관적으로 보이기 때문에 눈에 띕니다.
은 정수를 인수로 받아들이고 배열의 해당 요소를 반환합니다. Array.prototype.at()
<code class="language-javascript">const arr = ["One", "Two", "Three"];</code>전화:
<code class="language-javascript">arr.at(0); // 返回 "One"</code>대괄호 표기
와 동일합니다. 차이점이 무엇인지 궁금해하실 수도 있습니다. 다음으로 이 접근 방식을 사용할 때의 이점을 살펴보겠습니다. array[0]
대신 Array.prototype.at()
을 사용해야 하는 몇 가지 시나리오를 살펴보겠습니다. Array[index]
<code class="language-javascript">const sports = ["basketball", "baseball", "football"];</code>배열의 마지막 요소 "football"을 가져오려면 다음과 같이 작성할 수 있습니다.
<code class="language-javascript">const lastElement = sports[sports.length - 1];</code>이것은 올바른 접근 방식이지만
방법을 사용하면 더 간결하게 작성할 수 있습니다. Array.prototype.at()
<code class="language-javascript">const lastElement = sports.at(-1);</code>가독성이 더 좋나요?
유형 추론
가 포함되지 않습니다. undefined
<code class="language-typescript">const arr: string[] = []; const element = arr[0]; console.log(element); // undefined</code>
의 유형은 element
이 아닌 string
으로 유추됩니다. string | undefined
일반적으로 우리는 액세스되는 배열 요소가 존재하는지 확인하려고 합니다.
<code class="language-typescript">const arr: string[] = []; const element = arr[0]; if (typeof element === 'string') console.log(element);</code>이상한 점은 TypeScript가
로 추론하는 요소 유형을 확인하고 있다는 것입니다. string
<code class="language-typescript">const element: string | undefined = arr[0];</code>그러나 완벽한 코드를 작성하기 위해 스스로 책임을 져서는 안 되기 때문에 이는 이상적이지 않습니다.
이 문제를 해결하기 위해 다음 두 가지 접근 방식을 취할 수 있습니다.
noUncheckedIndexedAccess
을 사용하면 두 가지 방법을 모두 수행할 필요가 없습니다. Array.prototype.at()
<code class="language-typescript">const arr: string[] = []; const element = arr.at(0); // string | undefined console.log(element);</code>
유형의 다른 값에 element
을 삽입하려고 하면 컴파일 오류가 발생합니다. string
<code class="language-javascript">const element = arr[1];</code>
Array.prototype.at()
을 사용하면 더 깔끔한 코드를 작성하고 추가 기능 및 구성을 추가하지 않아도 됩니다.
Array.prototype.at()
Mozilla 개발자 네트워크 설명: 링크 (실제 링크로 대체하세요)
위 내용은 Array[index] 대신 Array.at() 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!