0% found this document useful (0 votes)
1 views9 pages

Lecture JS - Array Iterators

The document explains Array Iterator Objects in JavaScript, specifically the methods values(), keys(), and entries() for iterating over arrays. It provides examples of how to use these methods to access array values, indexes, and [index, value] pairs. Additionally, it briefly mentions the for...of and for...in loops for iterating over iterable objects and array indexes, respectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views9 pages

Lecture JS - Array Iterators

The document explains Array Iterator Objects in JavaScript, specifically the methods values(), keys(), and entries() for iterating over arrays. It provides examples of how to use these methods to access array values, indexes, and [index, value] pairs. Additionally, it briefly mentions the for...of and for...in loops for iterating over iterable objects and array indexes, respectively.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Array Iterator

Objects
The Array Iterator Objects in JavaScript—values(), keys(), and entries()—allow you to manually
iterate over an array’s elements, indexes, or both. These methods return iterator objects, which
conform to the iterator protocol.
values()
Returns a new Array Iterator that contains the values for each index in the array.

const arr = ['a', 'b', 'c'];


const iterator = arr.values();
for (const value of iterator) {
console.log(value); // 'a', 'b', 'c'
}
keys()
Returns a new Array Iterator that contains the keys (indexes) for each index in the array.

const arr = ['a', 'b', 'c'];


const iterator = arr.keys();
for (const key of iterator) {
console.log(key); // 0, 1, 2
}
entries()
Returns a new Array Iterator that contains [index, value] pairs for each index in the array.

const arr = ['a', 'b', 'c'];


const iterator = arr.entries();
for (const [index, value] of iterator) {
console.log(index, value);
// 0 'a'
// 1 'b'
// 2 'c'
}
.next()
const arr = ['x', 'y'];
const iterator = arr.entries();

console.log(iterator.next()); // { value: [0, 'x'], done: false }


console.log(iterator.next()); // { value: [1, 'y'], done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Misc.
for...of
Iterates over the values of an iterable object like an array.

const arr = [1, 2, 3];


for (const value of arr) {
console.log(value); // 1, 2, 3
}
for...in
Iterates over the keys (indexes) of an array (not recommended for arrays).

const arr = [1, 2, 3];


for (const index in arr) {
console.log(arr[index]); // 1, 2, 3
}

You might also like