![]() |
The Array.prototype.at() method in TypeScript allows you to access elements in an array using both positive and negative indices. It returns the element stored at the specified index if the index is valid, otherwise it returns undefined. Syntax:array.at(index: number): T | undefined Parameter:
Return Value:
Examples of Array.prototype.at() MethodExample 1: Accessing Elements with Valid IndicesIn this example, we will demonstrate how to access elements using both positive and negative indices. Example 1: The below code will demonstrate that how to access elements by passing valid negative and positive both kinds of indices as parameters.
Output: Passed index is 1, will return 2nd element: 2
Passed index is -1, will return last value element: true
Passed index is 2, will return 3rd element: TypeScript Example 2: Handling Invalid IndicesIn this example, we will show the behavior of the at() method when passing invalid index positions.
Output: Passed invalid index as -5: undefined
Passed invalid index as 6: undefined
Passed invalid index as -7: undefined FAQs – Array.prototype.at() MethodWhat does the at() method return if the index is out of bounds?
Can the at() method be used with strings as well?
What is the advantage of using the at() method over bracket notation?
Is the at() method supported in all JavaScript environments?
How does the at() method handle negative indices?
|
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |