JavaScript Array values() method
The values()
method in JavaScript is used to create a new array iterator object that contains the values of each element in an array. This method is useful when you need to iterate over the values of an array without needing their corresponding keys (indices).
Syntax:
Return Value:
- A new
Array Iterator
object that contains the values of the array.
Key Points:
- The
values()
method does not modify the original array. - The resulting iterator can be traversed using methods like
next()
, or it can be used in a loop (such as afor...of
loop) to iterate over the values.
Example 1: Basic usage
Example 2: Using a for...of loop
You can easily iterate over the values using a for...of
loop:
Example 3: Converting to an Array
If you want to convert the iterator into an array of values, you can use Array.from()
:
Example 4: Nested Arrays
The values()
method can be used with nested arrays as well:
Summary:
- The
values()
method provides a convenient way to access the values of elements in an array without needing their indices. - It returns an iterator, allowing for flexible iteration over the values in various contexts, such as loops and transformations.
- This method is particularly useful for scenarios where you only need the values from an array, simplifying code and enhancing readability.