Check for an instance of ArrayBufferView?
Asked Answered
P

3

16

Background

With a bit of research I've found that, although ArrayBufferView wasn't initially exposed (through [NoInterfaceObject]) there appeared to be broad agreement that it should be, due to my described use case.

The initial agreement was to expose the ArrayBufferView constructor on the DOMWindow namespace, which was implemented in Safari (and still works in 6.1.1) and Chrome, but was then pulled from Chrome in favour of a static method ArrayBuffer.isView().

Meanwhile, Mozilla are (still) talking about implementing ArrayBuffer.isView().

In brief:

  • Safari exposes the ArrayBufferView constructor

  • Chrome has ArrayBuffer.isView()

  • Firefox has nothing

  • IE - I haven't even got near yet...

Question

So, my question. What's the most succinct way to check if an object is an instance of ArrayBufferView?

Petersburg answered 13/2, 2014 at 11:57 Comment(0)
P
11

I would use either:

function isAbv(value) {
    return value && value.buffer instanceof ArrayBuffer && value.byteLength !== undefined;
}

or:

var ArrayBufferView = Object.getPrototypeOf(Object.getPrototypeOf(new Uint8Array)).constructor;
function isAbv(value) {
    return value instanceof ArrayBufferView;
}
Pinkster answered 15/2, 2014 at 15:53 Comment(0)
S
1

Better answer I guess:

var arr = new Float64Array(100);

arr instanceof (new Uint16Array()).constructor.prototype.__proto__.constructor //true

works in Chrome & Firefox, maybe other browsers too

Sleety answered 17/10, 2017 at 17:7 Comment(0)
L
1

ArrayBuffer.isView is supported on all modern browsers.

const b = new Uint8Array()
ArrrayBuffer.isView(b) // true
Landwehr answered 13/12, 2022 at 22:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.