简体   繁体   中英

Why can't I use Object.keys() on Set or Map?

I'm trying to use console.log to see the properties of a Set object (like size ). But if I try to log the keys in a Set, I get an empty array:

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(3);

let keys = Object.keys(mySet);
console.log(keys); 

// Output: []

The same thing happens when I use a Map:

let myMap = new Map();
myMap.set('1', 1);
myMap.set('2', 2);
myMap.set('3', 3);

let keys = Object.keys(myMap);
console.log(keys); 

// Output: []

Why do you expect them to be available as keys? The Set and Map specs never promised it. The keys/values are available using the corresponding APIs.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map

{Map, Set}.prototype.keys() has another behavior both returns a new Iterator object not an array with keys:

from Map MDN reference :

Map.prototype.keys() Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

from Set MDN reference :

Set.prototype.keys() Is the same function as the values() function and returns a new Iterator object that contains the values for each element in the Set object in insertion order.

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