Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript array.values()
The array.values() method returns an iterator object that contains all the values of an array. This method provides a way to iterate through array values using for...of loops or iterator methods.
Syntax
array.values()
Parameters
This method takes no parameters.
Return Value
Returns an Array Iterator object containing the values of the array.
Example: Using array.values() with for...of Loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Values Example</title>
</head>
<body>
<h2>JavaScript array.values()</h2>
<div id="output"></div>
<button onclick="showValues()">Show Array Values</button>
<script>
let animals = ["cow", "bull", "lion", "tiger", "sheep"];
function showValues() {
let output = document.getElementById("output");
output.innerHTML = "<h3>Array Values:</h3>";
for (let value of animals.values()) {
output.innerHTML += value + "<br>";
}
}
// Display original array first
document.getElementById("output").innerHTML =
"<h3>Original Array:</h3>" + animals.join(", ");
</script>
</body>
</html>
Example: Using Iterator Methods
let fruits = ["apple", "banana", "orange"]; let iterator = fruits.values(); // Using next() method console.log(iterator.next().value); // apple console.log(iterator.next().value); // banana console.log(iterator.next().value); // orange console.log(iterator.next().done); // true
apple banana orange true
Example: Converting Iterator to Array
let numbers = [1, 2, 3, 4, 5]; let valuesArray = Array.from(numbers.values()); console.log(valuesArray); // [1, 2, 3, 4, 5] console.log(typeof valuesArray); // object (array)
[ 1, 2, 3, 4, 5 ] object
Comparison with Other Array Methods
| Method | Returns | Content |
|---|---|---|
values() |
Iterator | Array values only |
keys() |
Iterator | Array indices only |
entries() |
Iterator | [index, value] pairs |
Browser Compatibility
The array.values() method is supported in all modern browsers. It was introduced in ES2015 (ES6).
Conclusion
The array.values() method provides an efficient way to iterate through array values using iterators. It's particularly useful with for...of loops and when you need to process array values sequentially.
Advertisements
