现在,我通过以下方式实现了
if (obj instanceof Uint8Array || obj instanceof Uint16Array || obj instanceof Uint32Array ......
队伍很长。 我知道针对对象的父类测试 instanceof 会产生 true,那么这些类型化数组中是否存在父类?我尝试了 TypedArray 但根据 chrome 它不存在。
有人知道类型化数组之间是否有基类吗?或者其他方法?
最佳答案
TypedArray
原型(prototype) does exist but is not exposed directly 。您可以使用 Object.getPrototypeOf
从任何类型化的 arry 子类中获取它,如下所示:
>> const TypedArray = Object.getPrototypeOf(Uint8Array)
>> console.log((new Uint32Array()) instanceof TypedArray)
true
因此,在范围内使用上面的 const TypedArray
,您的检查就变成了:
if (obj instanceof TypedArray) { ... }
关于javascript - 如何判断一个对象是否是类型化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65824084/