Home > other >  Why does Array.isArray not work for a typed array?
Why does Array.isArray not work for a typed array?

Time:06-10

I'm using Chrome Version 101.0.4951.64 (Official Build) (arm64) on a new m1 macbook pro. Is it expected behavior that

Array.isArray(new Float32Array([0, 1, 2]))

returns false?

console.log(Array.isArray(new Float32Array([1, 2, 3])));

CodePudding user response:

Typed arrays are not technically arrays, they are TypedArrays and have their own type:

let floatArr = new Float32Array();
console.log(Object.prototype.toString.call(floatArr));
console.log(Object.prototype.toString.call([]));

And according to the MDN web docs:

JavaScript typed arrays are array-like objects
...
However, typed arrays are not to be confused with normal arrays, as calling Array.isArray() on a typed array returns false.

CodePudding user response:

TypedArrays aren't Arrays.

console.log(new Uint32Array instanceof Array)

The equivalent of Array.isArray() for TypedArrays is ArrayBuffer.isView():

const typed = new Float32Array(1024);
const arr = new Array(1024);

console.log(Array.isArray(typed));      // false
console.log(Array.isArray(arr));        // true
console.log(ArrayBuffer.isView(typed)); // true
console.log(ArrayBuffer.isView(arr));   // false

with the particularity that it will also return true for DataView objects.

  • Related