该新特性属于 ECMAScript 2015(ES6)规范,在使用时请注意浏览器兼容性。
概述
数组的 keys() 方法返回一个数组索引的迭代器。
语法
arr.keys()
示例
例子:演示一下迭代器的执行原理
var arr = ["a", "b", "c"];
var iterator = arr.keys();
console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
例子:索引迭代器会包含那些没有对应元素的索引
var arr = ["a", , "c"]; var sparseKeys = Object.keys(arr); var denseKeys = [...arr.keys()]; console.log(sparseKeys); // [0, 2] console.log(denseKeys); // [0, 1, 2]
规范
| 规范名称 | 规范状态 | 备注 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) Array.prototype.keys |
Standard |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | 38 | 28 (28) | 未实现 | 25 | 7.1 |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | 未实现 | 未实现 | 28.0 (28) | 未实现 | 未实现 | iOS 8 |