简体   繁体   中英

Why we can not empty Float32Array() array by assigning length equal to zero, like other normal array? In Javascript

Let's suppose we have two arrays.

var normal = new Array(1,2,3,4);
var float32 = new Float32Array(4);

Now its possible to empty normal array by

normal.length = 0;

But, In the case of float32 I am unable to empty array by

float32.lenght = 0;

Array remains same. why??

Array remains same. why??

Float32Array is a TypedArray and as per docs

The length property is an accessor property whose set accessor function is undefined, meaning that you can only read this property.

hence even after setting the length property to 0 , its value remain as is

var arr = new Float32Array([21,31]);
arr.length = 0;
console.log(arr.length) //2

Because your Float32Array is just a view over an underlying ArrayBuffer , which itself is a fixed-length raw binary data buffer .

At the risk of simplifying a bit, once an ArrayBuffer has been assigned memory slots, it will stay in the same slots, and you won't be able to modify its byteLength*.


*Actually, you can empty the object which holds the data, by transferring its data, even if transferring it just for emptying the ArrayBuffer object makes no sense since you won't be able to change its length again (no push):

 var arr = new Float32Array(56); console.log('before transfer', arr.length); postMessage(arr, '*', [arr.buffer]); console.log('after transfer', arr.length); 

This might be a bit controversial but...

This state of affairs exists because the typed arrays are not generally meant for use by JavaScript developers. They are there to make JavaScript a more attractive target for compilers like emscripten.

Arrays in C/C++ are fixed-size (which is why you declare the size in bytes of those arrays when you create them in JS) and can only hold elements of a single type, so the idea of altering their length makes no sense and would invalidate a lot of the assumptions that C/C++ compilers get to make because of it.

The whole point of having typed arrays is to allow faster computations for expensive processes (eg 3D graphics) and if you had to check every access for an out-of-bounds access it would be too slow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM