访问Safari 7.1+中的Map值 [英] Access to Map values in Safari 7.1+

查看:63
本文介绍了访问Safari 7.1+中的Map值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Safari在7.1及更高版本中支持ES6 Maps and Sets( MDN )。
我在我的应用程序中使用一个Map,并且在某些时候想要访问这些值。在地图上调用 values()函数似乎就像去的方式并返回一个迭代器。通过在返回的Iterator上调用 next(),应该可以遍历这些值。这在Chrome中可以正常工作,但Safari会发生奇怪的事情。调用 values()时返回一个 Map Iterator ,但返回的迭代器没有 next () function。

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

我缺少一些明显的东西,还是只有Safari实现部分?
有另一种方式来访问值吗?使用 for..of 构造不是一个选项,因为这是新的语法,在旧版本的浏览器中不支持(我使用es6集合垫片)。 p>

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).

推荐答案

这确实似乎是Safari 7.1和8的错误。我设法解决这个问题,首先检查下一个函数是可用的,如果没有,我使用构造的。因为这是ES6前的无效语法,所以我不得不将它包装在一个 eval 语句中:

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 */");
}

这篇关于访问Safari 7.1+中的Map值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆