Array.prototype.values()
The values()
method returns a new
array iterator object that contains the values for each
index in the array.
Syntax
values()
Return value
A new Array
iterator object.
Examples
Iteration using for...of loop
const arr = ['a', 'b', 'c', 'd', 'e'];
const iterator = arr.values();
for (let letter of iterator) {
console.log(letter);
} //"a" "b" "c" "d" "e"
Array.prototype.values is default implementation of Array.prototype[Symbol.iterator].
Array.prototype.values === Array.prototype[Symbol.iterator] //true
Iteration using .next()
const arr = ['a', 'b', 'c', 'd', 'e'];
const iterator = arr.values();
iterator.next(); // Object { value: "a", done: false }
iterator.next().value; // "b"
iterator.next()["value"]; // "c"
iterator.next(); // Object { value: "d", done: false }
iterator.next(); // Object { value: "e", done: false }
iterator.next(); // Object { value: undefined, done: true }
iterator.next().value; // undefined
Warning: The array iterator object is one use or temporary object
example:
const arr = ['a', 'b', 'c', 'd', 'e'];
const iterator = arr.values();
for (let letter of iterator) {
console.log(letter);
} //"a" "b" "c" "d" "e"
for (let letter of iterator) {
console.log(letter);
} // undefined
reason: When next().done=true
or
currentIndex>length
the for..of
loop ends.
See Iteration protocols.
Value: there are no values stored in the array Iterator object; instead it stores the address of the array used in its creation and so depends on the values stored in that array.
const arr = ['a', 'b', 'c', 'd', 'e'];
const iterator = arr.values();
console.log(iterator); // Array Iterator { }
iterator.next().value; // "a"
arr[1]='n';
iterator.next().value; // "n"
Note: If the values in the array changed the array iterator object values change too.
Specifications
Specification |
---|
ECMAScript Language Specification # sec-array.prototype.values |
Browser compatibility
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
values | ChromeFull support66 | EdgeFull support12 | FirefoxFull support60 | Internet ExplorerNo supportNo | OperaFull support53 | SafariFull support9 | WebView AndroidFull support66 | Chrome AndroidFull support66 | Firefox for AndroidFull support60 | Opera AndroidFull support47 | Safari on iOSFull support9 | Samsung InternetFull support9.0 | DenoFull support1.0 | Node.jsFull support10.9.0 |
Legend
- Full support
- Full support
- No support
- No support
- See implementation notes.
- User must explicitly enable this feature.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.