如何可靠地检查对象是EcmaScript 6地图/集? [英] How to reliably check an object is an EcmaScript 6 Map/Set?
问题描述
我只想检查一个对象是 Map
或设置
而不是 Array
。
I just want to check that an object is a Map
or Set
and not an Array
.
检查数组我使用lodash的 _。isArray
。
to check an Array I'm using lodash's _.isArray
.
function myFunc(arg) {
if (_.isArray(arg)) {
// doSomethingWithArray(arg)
}
if (isMap(arg)) {
// doSomethingWithMap(arg)
}
if (isSet(arg)) {
// doSomethingWithSet(arg)
}
}
b $ b
如果我要实现 isMap
/ isSet
,它需要什么样子?我想让它能够捕获 Map
/ 的子类。如果可能的话,还要设置
。
If I were to implement isMap
/isSet
, what does it need to look like? I'd like for it to be able to catch subclasses of Map
/Set
if possible as well.
推荐答案
情况与前ES5方法类似,可以正确可靠地检测数组。请参阅这篇精彩文章 isArray
的可能缺陷。
The situation is similar to pre-ES5 methods to detect arrays properly and reliably. See this great article for the possible pitfalls of implementing isArray
.
我们可以使用
-
obj.constructor == Map
/设置
,但不起作用 -
obj instanceof Map
/设置$ c $
-
obj [Symbol.toStringTag] ==Map
/设置
,但可以轻易被欺骗。
obj.constructor == Map
/Set
, but that doesn't work on subclass instances (and can easily be deceived)obj instanceof Map
/Set
, but that still doesn't work across realms (and can be deceived by prototype mangling)obj[Symbol.toStringTag] == "Map"
/"Set"
, but that can trivially be deceived again.
要真正确定,我们需要测试一个对象是否具有 [[MapData]]
/ [[SetData] ]
内部插槽。这不是那么容易访问 - 它的内部。我们可以使用hack,虽然:
To be really sure, we'd need to test whether an object has a [[MapData]]
/[[SetData]]
internal slot. Which is not so easily accessible - it's internal. We can use a hack, though:
function isMap(o) {
try {
Map.prototype.has.call(o); // throws if o is not an object or has no [[MapData]]
return true;
} catch(e) {
return false;
}
}
function isSet(o) {
try {
Set.prototype.has.call(o); // throws if o is not an object or has no [[SetData]]
return true;
} catch(e) {
return false;
}
}
$ c> instanceof - 它是简单,可理解,性能和工作在最合理的情况下。或者你立即去鸭子输入,只检查对象是否有 /
get
/ set
/ delete
/ add
/ c $ c>方法。
For common use, I'd recommend instanceof
- it's simple, understandable, performant, and works for most reasonable cases. Or you go for duck typing right away and only check whether the object has has
/get
/set
/delete
/add
/delete
methods.
这篇关于如何可靠地检查对象是EcmaScript 6地图/集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!