MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

 keys() 方法返回一个新的Array迭代器,它包含数组中每个索引的键。

let arr = ["a", "b", "c"];

let iterator = arr.keys();
// undefined

console.log(iterator);
// Array Iterator {}

console.log(iterator.next()); 
// Object {value: 0, done: false}

console.log(iterator.next()); 
// Object {value: 1, done: false}

console.log(iterator.next()); 
// Object {value: 2, done: false}

console.log(iterator.next()); 
// Object {value: undefined, done: true}

语法

arr.keys()

返回值 

一个新的 Array 迭代器对象。

示例

例子:演示一下迭代器的执行原理

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

相关链接

文档标签和贡献者

 此页面的贡献者: micheal-death, xgqfrms-GitHub, ziyunfei, 200OK
 最后编辑者: micheal-death,