2

I'm using Set to handle my task. But when I debugged, I got

mySet.has is not a function

So my question is how to check if It's a Set. Like for the Array has Array.isArray(obj).

bird
  • 1,751
  • 13
  • 26

3 Answers3

8

You can use instanceof

let a = new Set()
let b = [1,2]

console.log(a instanceof Set)
console.log(b instanceof Set)

On side note :-

You can also use [] instanceof Array. However, Array.isArray was created for a specific purpose: avoiding an issue with instanceof. Namely, window1.Array != window2.array; thus, new window1.Array() instanceof window2.Array == false. Same logic holds for Set. As long as you don't mess with multiple global environments, instanceof is fine. If you do, b.toString() == "[object Set]" might be better. Thanks to @andman for pointing out.

Code Maniac
  • 35,187
  • 4
  • 31
  • 54
1

may be you can use instanceof.

read more here.

let s1 = new Set()
let s2 = ['a','b','c']

console.log(s1 instanceof Set)
console.log(s2 instanceof Set)
1

Another possibility for this check could be using Object.prototype.constructor:

let a = new Set([1,2]);
let b = [1,2];

console.log("a is a Set? " + (a.constructor === Set));
console.log("b is a Set? " + (b.constructor === Set));
Shidersz
  • 16,261
  • 2
  • 18
  • 44