Feature of JavaScript in Visual Studio 2012: Typed Arrays

Introduction

 
In my previous article, you learned about "Prototype and Prototype Inheritance in JavaScript". In this article, I will tell you about one more new feature of JavaScript in Visual Studio 2012, Typed Arrays.
 
A Typed Array can be used to handle binary data from various sources such as Network Protocols, Binary File Formats, and Raw Graphic Buffers. Typed Arrays can also be used to manage in-memory Binary Data with a well-known Byte Layout.
 
Step 1
 
Now I will tell you how to use an Array Buffer Object as the response of an XMLHttpRequest through an example. You can manipulate the bytes in the response using the various methods of the Data View Object, or by copying the bytes into the appropriate Typed Array.
 
First of all, add a JavaScript page to your Windows or Web Application. This can be done by right-clicking on your application and then "Add" | "New Item...".
 
prototype1.jpg
 
Now in the New Item list select the JavaScript Style Sheet.
 
prototype2.jpg
 
Step 2
 
Now in the Style Sheet write the following code:
  1. ...  
  2. <div id="xhrDiv"></div>  
  3. ...  
  4. var name = "http://www.microsoft.com";  
  5. var xhrDiv = document.getElementById("xhrDiv");  
  6.    
  7. var req = new XMLHttpRequest();  
  8. req.open("GET", name, true);  
  9. req.responseType = "arraybuffer";  
  10. req.onreadystatechange = function () {  
  11. if (req.readyState == req.DONE) {  
  12.     var arrayResponse = req.response;  
  13.     var dataView = new DataView(arrayResponse);  
  14.     var ints = new Uint32Array(dataView.byteLength / 4);  
  15.    
  16.     xhrDiv.style.backgroundColor = "#00FF00";  
  17.     xhrDiv.innerText = "Array is " + ints.length + "uints long";  
  18.     }  
  19. }  
  20. req.send(); 
Step 3
  • Array Buffer: An Array Buffer object represents a buffer of raw data that is used to store data for various Typed Arrays. You can't read from or write to an Array Buffer but you can pass it to a Typed Array or Data View Buffer to interpret the Raw Buffer. You can use an Array Buffer to store any kind of data that can also be mixed data.
     
  • DataView: You can use a DataView object to read and write various kinds of Binary Data to any location in the Array Buffer.
Step 4
 
Typed Array: The Typed Array types represent views of an Array Buffer Object that can be indexed and manipulated. All Array types are of fixed lengths.
 
Name Size(in Bytes) Description
Int8Array Object 1 Eight Bit two's complement signed integer
Uint8Array Object 1 Eight Bit Unsigned integer
Int16Array Object 2 Sixteen bit two's complement signed integer
Uint16Array Object 2 Sixteen Bit Unsigned Integer
Int32Array Object 4 Thirty-Two Bit two's complement signed integer
Uint32Array Object 4 Thirty-Two Bit Unsigned Integer
Float32Array Object 4 Thirty-Two Bit IEEE Floating point
Float64Array Object 8 Sixty Four Bit IEEE Floating point