How to reliably check an object is an EcmaScript 6 Map/Set?(如何可靠地检查对象是 EcmaScript 6 Map/Set?)
问题描述
我只想检查一个对象是 Map 或 Set 而不是 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)
}
}
如果我要实现 isMap/isSet,它需要是什么样的?如果可能的话,我希望它能够捕获 Map/Set 的子类.
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/Set,但这对子类实例不起作用(并且很容易被欺骗)obj instanceof Map/Set,但这仍然不能跨领域工作(并且可能被原型修改所欺骗)obj[Symbol.toStringTag] == "Map"/"Set",但是这很容易被再次欺骗.
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;
}
}
对于一般用途,我推荐 instanceof - 它简单、易懂、高效,适用于大多数合理的情况.或者你马上去鸭子打字,只检查对象是否有 has/get/set/delete/add/delete 方法.
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 Map/Set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何可靠地检查对象是 EcmaScript 6 Map/Set?
基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
