The Array.prototype.entries() method in TypeScript returns a new array iterator object that contains the key/value pairs for each index in the array. This method is useful when you need to iterate over the key/value pairs in the array.
Note: In TypeScript, the entries() method is not available directly on arrays as it is in JavaScript for objects, but we can achieve a similar result through a different approach.
Syntax:Object.entries(arrayName) Return Value:- An iterator that yields key-value pairs, where keys are indices and values are array elements.
Examples of Array entries() MethodExample 1: Accessing Student Names and Indices Using entries()In this example, we will use the entries() method to iterate over the student names array and access their indices and values.
JavaScript
const students: string[] = ["Pankaj", "Ram", "Shravan"];
const iterator = students.entries();
for (let entry of iterator) {
const [index, value] = entry;
console.log(`Index: ${index}, Value: ${value}`);
}
Output:
Index: 0, Value: Pankaj
Index: 1, Value: Ram
Index: 2, Value: Shravan Example 2: Accessing Number Array Elements with Indices Using a While LoopIn this example, we will use the entries() method and a while loop to iterate over a number array and access their indices and values.
JavaScript
const numbers: number[] = [10, 20, 30];
const iterator = numbers.entries();
let result = iterator.next();
while (!result.done) {
const [index, value] = result.value;
console.log(`Index: ${index}, Value: ${value}`);
result = iterator.next();
}
Output:
Index: 0, Value: 10
Index: 1, Value: 20
Index: 2, Value: 30 Supported Browsers:- Google Chrome
- Edge
- Firefox
- Opera
- Safari
FAQs – TypeScript Array entries() MethodWhat does the entries() method return?The entries() method returns a new array iterator object that contains the key/value pairs for each index in the array.
Can the entries() method be used on objects in TypeScript?No, the entries() method is specifically for arrays. However, you can use Object.entries() for objects to get a similar result.
Is the entries() method available in all modern browsers?Yes, the entries() method is supported in all modern browsers, including Google Chrome, Edge, Firefox, Opera, and Safari.
How can I use entries() in a for…of loop?You can use the entries() method in a for…of loop by iterating over the iterator object returned by entries(). Each iteration will yield a key-value pair.
What is the difference between Object.entries() and Array.prototype.entries()?Object.entries() is used to return an array of a given object’s own enumerable string-keyed property [key, value] pairs, while Array.prototype.entries() returns an array iterator object that contains key/value pairs for each index in an array.
|