How to check if a variable is a typed array in javascript?
ArrayBuffer.isView
should help you out.
var data = [0,1,2]var dataBuffer = new ArrayBuffer( data )var dataBufferView = new Float32Array( data )ArrayBuffer.isView(data) //falseArrayBuffer.isView(dataBuffer) //falseArrayBuffer.isView(dataBufferView) //truedataBuffer instanceof ArrayBuffer //true
If you're happy with it being a Float32Array
or a subclass of Float32Array
and they'll be from the same realm (loosely, window) as the code you're checking, see Anton's answer using instanceof
.
If you need to know that it's specifically a Float32Array
and not a subclass (and its from the same realm), you could use yourObject.constructor === Float32Array
:
if (yourObject.constructor === Float32Array) { // It's a Float32Array}
Live example:
But note that will fail if the object originates in a different realm (like another frame), because different environments have different Float32Array
constructors (even though they do the same thing).
If you need to support cases where constructor
won't work, you can use the Object.prototype.toString.call(yourObject)
trick. That returns a useful string for all of the JavaScript built-in types ([object Array]
, [object Date]
, etc.) Per specification, Object.prototype.toString
when applied to a typed array must return the string in the format "[object TypedArrayNameHere]"
.
So:
if (Object.prototype.toString.call(yourObject) === "[object Float32Array]") { // It's a Float32Array}
Live example:
Note that it's possible to create objects that lie about their type, making Object.prototype.toString
return the same thing it would return for (say) Float32Array
:
You also can use yourObject instanceof Float32Array
construction.It returns true
if your object is an instance of Float32Array
and false
in other case.
if (yourObject instanceof Float32Array) { // your code here}