最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check for an instance of ArrayBufferView? - Stack Overflow

programmeradmin4浏览0评论

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.

  • Firefox
  • Chrome
  • Safari

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?

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.

  • Firefox
  • Chrome
  • Safari

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?

Share Improve this question edited Feb 24, 2014 at 16:48 james asked Feb 13, 2014 at 11:57 jamesjames 4,5733 gold badges33 silver badges43 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 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;
}

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

ArrayBuffer.isView is supported on all modern browsers.

const b = new Uint8Array()
ArrrayBuffer.isView(b) // true
发布评论

评论列表(0)

  1. 暂无评论