06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3<br />

You have to use the array literal syntax if you want to initialize an array with a single<br />

element and the element happens to be a number. If you pass a single number value<br />

to the Array() constructor or function, <strong>JavaScript</strong> considers this parameter as the<br />

length of the array, not as a single element:<br />

var arr = [10];<br />

var arr = Array(10); // Creates an array with no element, but with<br />

arr.length set to 10<br />

// The above code is equivalent to<br />

var arr = [];<br />

arr.length = 10;<br />

<strong>JavaScript</strong> does not have an explicit array data type. However, you can use the<br />

predefined Array object and its methods to work with arrays in your applications.<br />

The Array object has methods to manipulate arrays in various ways, such as joining,<br />

reversing, and sorting them. It has a property to determine the array length and<br />

other properties for use with regular expressions.<br />

You can populate an array by assigning values to its elements:<br />

var days = [];<br />

days[0] = "Sunday";<br />

days[1] = "Monday";<br />

You can also populate an array when you create it:<br />

var arr_generic = new Array("A String", myCustomValue, 3.14);<br />

var fruits = ["Mango", "Apple", "Orange"]<br />

In most languages, the elements of an array are all required to be of the same type.<br />

<strong>JavaScript</strong> allows an array to contain any type of values:<br />

var arr = [<br />

'string', 42.0, true, false, null, undefined,<br />

['sub', 'array'], {object: true}, NaN<br />

];<br />

You can refer to elements of an Array using the element's index number. For<br />

example, suppose you define the following array:<br />

var days = ["Sunday", "Monday", "Tuesday"]<br />

You then refer to the first element of the array as colors[0] and the second element<br />

of the array as colors[1]. The index of the elements starts with 0.<br />

[ 87 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!