values()
方法返回一个新的 Array Iterator
对象,该对象包含数组每个索引的值
语法
arr.values()
返回值
一个新的 Array
迭代对象。
示例
使用 for...of 循环进行迭代
let arr = ['w', 'y', 'k', 'o', 'p'];
let eArr = arr.values();
for (let letter of eArr) {
console.log(letter);
} //"w" "y "k" "o" "p"
Array.prototype.values 是 Array.prototype[Symbol.iterator] 的默认实现。
Array.prototype.values === Array.prototype[Symbol.iterator] // true
使用 .next() 迭代
var arr = ['a', 'b', 'c', 'd', 'e']; var 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 } iteraroe.next().value; // undefined
一次性:数组迭代器是一次性的,或者说临时对象
例子:
var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } //"a" "b" "c" "d" for (let letter of iterator) { console.log(letter); } // undefined
解释: 当 next().done=true
或 currentIndex>length
时, for..of
循环结束。参见 Iteration protocols 。
值: 数组迭代器中存储的是原数组的地址,而不是数组元素值。
var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); console.log(iterator); // Array Iterator { } iterator.next().value; // "a" arr[1] = 'n'; iterator.next().value; // "n"
如果数组中元素改变,那么迭代器的值也会改变
TODO: please write about why we need it, use cases.
规范
规范名称 | 规范状态 | 备注 |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262) Array.prototype.values |
Standard | 首次定义 |
ECMAScript (ECMA-262) Array.prototype.values |
Living Standard |
浏览器兼容性
BCD tables only load in the browser
The compatibility table in 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.