I need a typed array, specifically a Float32Array, of all zeros. I was thinking that I would have to clear it manually, but I noticed that when I declared it, it was already zeroed out. Is this something that is specified in the spec? Can I rely on this behavior?
JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast.
Normal arrays can be as fast as typed arrays if you do a lot of sequential access. Random access outside the bounds of the array causes the array to grow. Typed arrays are fast for access, but slow to be allocated. If you create temporary arrays frequently, avoid typed arrays.
Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.
The ArrayBuffer object is used to represent a generic, fixed-length raw binary data buffer. It is an array of bytes, often referred to in other languages as a "byte array".
According to JavaScript's Typed Array Specification, contents are initialized to 0. So you should be able to rely on this behavior.
Be aware that typed arrays don't have very good cross browser support yet. Chrome, Safari, Firefox, and Opera support it, but Internet Explorer only introduced support in IE10.
I should also mention that typed arrays are currently extremely slow in Safari compared to normal arrays. For this reason, you're probably better off avoiding typed arrays unless you aren't targeting Safari. Using normal arrays, all array values are initialized as undefined
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With