How To Check Object Is A Set?
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).
Solution 1:
You can use instanceof
let a = newSet()
let b = [1,2]
console.log(a instanceofSet)
console.log(b instanceofSet)
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.
Solution 2:
may be you can use instanceof
.
read more here.
let s1 = newSet()
let s2 = ['a','b','c']
console.log(s1 instanceofSet)
console.log(s2 instanceofSet)
Solution 3:
Another possibility for this check could be using Object.prototype.constructor:
let a = newSet([1,2]);
let b = [1,2];
console.log("a is a Set? " + (a.constructor === Set));
console.log("b is a Set? " + (b.constructor === Set));
Post a Comment for "How To Check Object Is A Set?"