Array.prototype.values()

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);
} //"a" "b" "c" "d"

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"

如果数组中元素改变,那么迭代器的值也会改变

规范

规范名称 规范状态 备注
ECMAScript 2015 (6th Edition, ECMA-262)
Array.prototype.values
Standard 首次定义
ECMAScript (ECMA-262)
Array.prototype.values
Living Standard

浏览器兼容性

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
valuesChrome Full support 66Edge Full support 12Firefox Full support 60IE No support NoOpera Full support 53Safari Full support 9WebView Android Full support 66Chrome Android Full support 66Firefox Android Full support 60Opera Android Full support 47Safari iOS Full support 9Samsung Internet Android Full support 9.0nodejs Full support 10.9.0
Full support 10.9.0
Full support 6.5.0
Notes Disabled
Notes The --harmony-array-prototype-values flag is required; the --harmony flag is not sufficient in this case.
Disabled From version 6.5.0: this feature is behind the --harmony-array-prototype-values runtime flag.
No support 0.12 — 4.0.0

Legend

Full support  
Full support
No support  
No support
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

相关链接