Access to Map values in Safari 7.1+

2020-04-08 06:39发布

问题:

Safari has support for ES6 Maps and Sets in version 7.1 and higher (MDN). I'm using a Map in my application and at some point want access to the values. Calling the values() function on the map seems like the way to go and returns an Iterator. By calling next() on the returned Iterator, one should be able to iterate over the values. This works fine in Chrome, but Safari does something strange. It returns a Map Iterator when calling values(), but the returned iterator has no next() function.

m = new Map();
m.set(1, "test");
m.set("2", false);
it = m.values(); // returns Map Iterator
it.next(); // TypeError: undefined is not a function

Am I missing something obvious, or is the Safari implementation only partial? Is there another way to get access to the values? Using the for..of construct is not an option because this is new syntax and is not supported in older browsers (for which I use the es6-collections shim).

回答1:

This indeed seems to be a bug with Safari 7.1 and 8. I managed to work around this issue by first checking if the next function was available and if not, I used the for...of construct. Because this is invalid syntax pre-ES6, I had to wrap it in an eval statement:

m = new Map();
m.set(1, "test");
m.set("2", false);
it = m.values(); // returns an Iterator
if (typeof it.next === 'function') {
    v = it.next();
    // do something with v here
} else {
    eval("for (v of iterator) /* do something with v here */");
}