Frage

I am playing with ECMAScript 6 symbols and maps in Node.JS v0.11.4 with the --harmony flag. Consider the following.

var a = Map();
a.set(Symbol(), 'Noise');

// Prints "1"
console.log(a.size);

Can the value 'Noise' be retrieved given the property is identified by an "anonymous" symbol key, which is guaranteed to be unique?

War es hilfreich?

Lösung

It is not possible to do it in node.js because the current version of v8 hasn't implemented iteration as indicated in this bug report.

We can confirm that by looking at the source code of v8's collection.js:

InstallFunctions($Map.prototype, DONT_ENUM, $Array(
    "get", MapGet,
    "set", MapSet,
    "has", MapHas,
    "delete", MapDelete,
    "clear", MapClear
));

But, as can be seen in ECMAScript 6 wiki, there should also be items(), keys(), and values(). v8 probably didn't implement these methods before, because it didn't support generators. But now it does since May of this year. It should be a just a matter of time until this is implemented.

If you need to have this functionality now, you can use map-set-for-each which polyfills forEach. You will need to modify it to add case 'symbol': after case 'object':.

a.forEach(function(value, key) {
  if (value === 'Noise') {
    console.log('Give mak the bounty');
  }
});

When v8 implements iteration of Map you will be able to find Noise like this:

for (let [key, value] of a) {
  if (value === 'Noise') {
    console.log('Upvotes for future');
  }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top