简体   繁体   中英

Why does the forEach() method exist for object keys but not array keys?

If I do this in node (v10.15.3):

Object.keys({test: 'test'}).forEach(() => console.log('gfg'));

I get:

gfg

If I do:

Array(3).keys()

I get:

Object [Array Iterator] {}

So I clearly have a type that is in some sense iterable.

However,

Array(3).keys().forEach(() => console.log('gfg'));

'Yields':

TypeError: Array(...).keys(...).forEach is not a function

Why does the forEach function not exist on this iterable object when the keys are derived from an array?

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 .

Convert it back to an array and then iterate over it

 ([...Array(3).keys()]).forEach(() => console.log('gfg')); 

you can see the keys() doesnt return an array

 console.log(Array.isArray(Array(3))); console.log(Array.isArray(Array(3).keys())); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM