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 (e.g. Sparse Array), they are created.
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.

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

for (let k of (xx.keys())) {
 console.log(k);
}
// 0
// 1
// 2
// 3
// 4