1

How can I determine that my data structure is of type Map()?

I've been looking everywhere, and can't find any method

I really want to get into using them because I can use objects as keys!

neaumusic
  • 10,027
  • 9
  • 55
  • 83

3 Answers3

4

You can use the instanceof opeartor

var map = new Map();
var arr = [];

console.log(map instanceof Map);
console.log(map instanceof Array);
console.log(arr instanceof Map);
console.log(arr instanceof Array);

From the Documentation

The instanceof operator tests whether an object has in its prototype chain the prototype property of a constructor.

Community
  • 1
  • 1
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • 2
    Also, be aware of [the difference between `Array.isArray` and `instanceof Array`](https://stackoverflow.com/questions/22289727/difference-between-using-array-isarray-and-instanceof-array). – Pavlo Oct 20 '16 at 07:47
  • @Pavlo Thanks for the useful link – Suren Srapyan Oct 20 '16 at 07:49
3

You could use either instanceof operator or the constructor property and check against the object.

For more information read this: What's the difference between using instanceof and checking the constructor?

var map = new Map();
var arr = [];

console.log(map instanceof Map);         // true
console.log(map instanceof Array);       // false
console.log(map.constructor === Map);    // true
console.log(map.constructor === Array);  // false

console.log(arr instanceof Map);         // false
console.log(arr instanceof Array);       // true
console.log(arr.constructor === Map);    // false
console.log(arr.constructor === Array);  // true

// caveat!
console.log(arr.constructor === Object); // false
console.log(map.constructor === Object); // false
console.log(arr instanceof Object);      // true
console.log(map instanceof Object);      // true
Community
  • 1
  • 1
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 2
    A useful reference link: [instanceof vs constructor](http://stackoverflow.com/questions/18055980/whats-the-difference-between-using-instanceof-and-checking-the-constructor) – Rajesh Oct 20 '16 at 07:38
0

You can even use Object.prototype.toString.call, though instanceof(@suren srapyan's answer) is more preferred

var a = [1,2,3];
var m = new Map()
a.forEach((x,i)=>m.set(i+1, x));

console.log(Object.prototype.toString.call(m))
Community
  • 1
  • 1
Rajesh
  • 24,354
  • 5
  • 48
  • 79