JS: Array.prototype.keys

By Xah Lee. Date: . Last updated: .

(new in ECMAScript 2015)

xArray.keys()
  • Return a Generator.
  • Each entry is the index of the array.
  • When index do not exist (as in sparse array), keys creates them.
console.log(["a", "b", "c"].keys());
// Object [Array Iterator] {}

// turn it into actual array
console.log(Array.from(["a", "b", "c"].keys()));
// [ 0, 1, 2 ]
// when index do not exist, keys creates them.

console.log([3, 4, , , 5]);
// [ 3, 4, <2 empty items>, 5 ]

for (let k of ([3, 4, , , 5].keys())) console.log(k);
// 0
// 1
// 2
// 3
// 4

Array Iterator