This is because Array.keys
is NOT the same as Object.keys
.
Array.keys
return an iterator (or, really an "Array Iterator"), it doesn't expose any array prototype because it does not return an array, though it can be looped:
for (var elem of Array(3).keys()){
console.log(elem);
}
// If you really want to use forEach...
[...Array(3).keys()].forEach(k => console.log('spread syntax -> ', k));
// Or using Array.from
Array.from(Array(3).keys()).forEach(k => console.log('Array.from ->', k));
So, what is the difference?
The difference is that Array.keys
returns an iterable, while Object.keys
returns an array. Because Array.keys
returns an iterable, it can't directly use array methods, because it's just an iterable (or, really, something that has a [Symbol.iterator]. Object.keys
, instead, returns an array, hence it can use any of its prototypes and, since it's an array, also happens to be iterable because, as mentioned before, Array
is a built in type that has a default iteration behavior.