The JavaScript Array.prototype.values() method returns a new array iterator object that contains the values for each index in the array. This method is particularly useful when you need to iterate over the values of an array using a loop or other iteration constructs.
Syntax
array.values();
Parameters
The values() method does not take any parameters.
Return Value
Value | Description |
---|---|
Iterator Object | Returns a new Array Iterator object that contains the values for each index in the array. |
Example 1: Basic Usage
This example demonstrates how to use the values() method to create an iterator and loop through the values of an array.
let arr = ['a', 'b', 'c']; let iterator = arr.values(); for (let value of iterator) { console.log(value); }
Output:
a
b
c
Example 2: Using values() with a while Loop
This example shows how to use the values() method with a while loop to iterate over the array values.
let arr = [1, 2, 3, 4]; let iterator = arr.values(); let result = iterator.next(); while (!result.done) { console.log(result.value); result = iterator.next(); }
Output:
1
2
3
4
Example 3: Combining values() with Other Array Methods
This example demonstrates how to use the values() method in combination with other array methods, such as map().
let arr = [10, 20, 30]; let iterator = arr.values(); let newArr = Array.from(iterator, value => value + 5); console.log(newArr);
Output:
[15, 25, 35]
Example 4: Using values() in a Generator Function
This example shows how to use the values() method within a generator function to yield array values.
function* generateValues(arr) { let iterator = arr.values(); for (let value of iterator) { yield value; } } let generator = generateValues([5, 10, 15]); for (let value of generator) { console.log(value); }
Output:
5
10
15
Example 5: Converting Iterator to Array
This example demonstrates how to convert an iterator returned by values() back into an array.
let arr = [100, 200, 300]; let iterator = arr.values(); let newArr = Array.from(iterator); console.log(newArr);
Output:
[100, 200, 300]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
66 | 14 | 60 | 53 | 9 |