确定对象是否是JavaScript中的Map

前端之家收集整理的这篇文章主要介绍了确定对象是否是JavaScript中的Map前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参见英文答案 > How to reliably check an object is an EcmaScript 6 Map/Set?                                    2个
我正在编写一个函数,如果传递给它的参数是JavaScript Map的实例,则返回true.

正如您可能已经猜到的那样,新的Map()会返回字符串对象,并且我们没有得到一个方便的Map.isMap方法.

这是我到目前为止:

  1. function isMap(v) {
  2. return typeof Map !== 'undefined' &&
  3. // gaurd for maps that were created in another window context
  4. Map.prototype.toString.call(v) === '[object Map]' ||
  5. // gaurd against toString being overridden
  6. v instanceof Map;
  7. }
  8. (function test() {
  9. const map = new Map();
  10. write(isMap(map));
  11. Map.prototype.toString = function myToString() {
  12. return 'something else';
  13. };
  14. write(isMap(map));
  15. }());
  16. function write(value) {
  17. document.write(`${value}

到目前为止一切都那么好,但是当测试帧之间的映射并且当覆盖toString()时,isMap失败了(I do understand why).

例如: