AJAX - The Complete Reference

(avery) #1

564 Part IV: Appendixes


You can also use the Array() constructor.

var variable = new Array(element1, element2, ... elementN);

If only one numeric argument is passed it is interpreted as the initial value for the
length property.
There are numerous properties and methods that can be run on arrays.

alert (myArray.length); // 4
myArray = myArray.reverse(); // reverse the array’s items

Beyond the apparent object syntax to manipulate arrays, it is important to note the close
relationship between arrays and objects in JavaScript. Object properties can be accessed not
only as objectName.propertyName but as objectName[‘propertyName’]. However, this does not
mean that array elements can be accessed using an object style; arrayName. 0 would not
access the first element of an array. Arrays are not quite interchangeable with objects in
JavaScript.
JavaScript 1.7, as supported in Firefox 2+, introduces an array-related “destructuring
assignment.” This allows you to access variables in an array outside of the array.

[a, b] = ["val1", "val2"];
alert(a);
alert(b);
// alerts val1 and then val2

One interesting thing we can do with this is a swap assignment without using
temporary variables. Instead of:

var i=1;
var j=2;
var t = i;
i=j;
j=t;

We use:

var i=1;
var j=2;
[i,j] = [j,i];

Another interesting feature is that we can easily return and consume multiple values:

function getBookInformation()
{
var author="Thomas A. Powell";
var subject="Ajax";
return [author, subject];
}
var [bookAuthor, bookSubject] = getBookInformation();
alert(bookAuthor);
alert(bookSubject);
Free download pdf