New methods of Array in JavaScript

Supported by all modern browsers, including IE9, methods for Web applications.

The features defined in JavaScript 6, or Harmony, are implemented in IE 10 and other browsers.

Buffer and view (Harmony)

The Buffer / View couple is widely used by Asm.js. A 'view' is a typed table used to access the contents of a buffer. For example an array of integer.
The example shows four numbers of 4 bytes in a 16-byte buffer.

ArrayBuffer/Int32Array :

var buffer = new ArrayBuffer(16);
var int32View = new Int32Array(buffer);
document.write(int32View.length); // displays 4.

reduce method (1.8)

The reduce method applies a function to an array. IE 9 support.
The example is the sum of the content.

Reduce :

function adding(a, b) { return a + b; }
var total = [0, 1, 2, 3].reduce(adding);  // total now is 6.

filter method (1.6)

The filter method uses a test function to an array and returns the validated elements into a new array. IE 9 support.
The example displays the number of selected elements.

Filter :

function compare(a) { return a >= 2; }
var testfilter = [0, 1, 2, 3].filter(compare);
document.write(testfilter.length); // displays 2.

map method (1.6)

The map method applies a function to a table so each element becomes in turn argument of the function, and returns a list of results for each element into a new array. Support IE 9.

Map :

var testmmap = [0, 9, 16].map(Math.sqrt);
document.write(testmmap[1]); // diplay 3, the square root.

every and some methods (1.6)

The every method tests whether all elements of an array support the function and returns true or false.
The some method tests whether the function returns true for at least one element. IE 9 Support
In the example with every all the elements are greater than 0.

Every, some:

var testever = [4, 9, 16].every(function(x) { return x > 0} );
document.write(testever); // displays true.

Object.keys() (1.8.5)

New method of Object that returns the list of keys or indexes of an array. Supported by IE 9.

Object.keys(tableau) :

var testk = { "a" : "orange" , "b" : "prune" };
var klist = Object.keys(testk);
document.write(klist); // displays the list of keys.

Objet JSON (1.5)

This object has two methods to parse a JSON object or convert it to a string. It is a way to display a formatted array. Supported by IE 8.
In the example, the string is converted into an object and "a" becomes a property.


var testjson = '{ "a": 1 }';
var pjson = JSON.parse(testjson);
document.write(pjson['a']);  // display true.

Can be added to the list of Array methods indexOf and lastIndexOf. They work like their counterparts in the String object.

© 2013