TypeScript Array keys() Method
Last Updated :
29 Jan, 2024
TypeScript keys()
method is not directly available on arrays. Instead, you can use the keys()
method from the Object
class to get the keys of an array. When applied to an array, Object.keys()
returns an array containing the string representations of the indices.
Syntax:
array.keys();
Parameter:
- The keys() method doesn’t accept any parameters.
Return Value:
- It returns an Array Iterator object that contains the keys (indices) of the array.
Example 1: Here, arrayKeys
will be an array containing the indices of myArray
(‘0’, ‘1’, ‘2’), because arrays in JavaScript are essentially objects where the indices are treated as keys.
Javascript
const myArray: string[] =
[ 'apple' , 'banana' , 'orange' ];
const arrayIndices: number[] =
Array.from(myArray.keys());
console.log(arrayIndices);
|
Output:
0
1
2
Example 2: Here, we will get the key and the value of the given string array.
Javascript
const names: string[] =
[ "Pankaj" , "Ram" , "Shravan" , "Jeetu" ];
for (const key of names.keys()) {
console.log(`Index: ${key}, Name: ${names[key as number]}`);
}
|
Output:
Index: 0, Name: Pankaj
Index: 1, Name: Ram
Index: 2, Name: Shravan
Index: 2, Name: Jeetu
Share your thoughts in the comments
Please Login to comment...