14.08.2016 Views

Beginning JavaScript with DOM Scripting and Ajax, 2nd Edition

Create successful ePaper yourself

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

Chapter 2 ■ Data <strong>and</strong> Decisions<br />

var arrayOne = new Array( "One", "Two", "Three","Four", "Five" );<br />

var arrayTwo = new Array( "ABC", "DEF", "GHI" );<br />

var arrayThree = new Array( "John", "Paul", "George","Ringo" );<br />

var joinedArray = arrayOne.concat( arrayTwo, arrayThree );<br />

document.write( "joinedArray has " + joinedArray.length + " elements" );<br />

document.write( joinedArray[0] + "" )<br />

document.write( joinedArray[11] + "" )<br />

<br />

<br />

<br />

The new array, joinedArray, has 12 items. The items in this array are the same as they were in each of the<br />

previous arrays; they’ve simply been concatenated together. The original arrays remain untouched.<br />

Converting an Array to a String <strong>and</strong> Back<br />

Having data in an array is h<strong>and</strong>y when you want to loop through it or select certain elements. However, when you<br />

need to send the data somewhere else, you probably should convert that data to a string. You can do that by looping<br />

through the array <strong>and</strong> adding each element value to a string. However, there is no need for that, because the Array<br />

object has a method called join() that does that for you. The method takes a string as a parameter. This string will be<br />

added in between each element.<br />

<br />

var arrayThree = new Array( "John", "Paul", "George","Ringo" );<br />

var lineUp=arrayThree.join( ', ' );<br />

alert( lineUp );<br />

<br />

The resulting string, lineUp, has the value "John, Paul, George, Ringo". The opposite of join() is split(),<br />

which is a method that converts a string to an array.<br />

<br />

var lineUp="John, Paul, George, Ringo";<br />

var members=lineUp.split( ', ' );<br />

alert( members.length );<br />

<br />

Sorting an Array<br />

The sort() method allows you to sort the items in an array into alphabetical or numerical order:<br />

<br />

<br />

<br />

var arrayToSort = new Array( "Cabbage", "Lemon","Apple", "Pear", "Banana" );<br />

arrayToSort.sort( );<br />

document.write(arrayToSort[0] + "" );<br />

document.write(arrayToSort[1] + "" );<br />

document.write(arrayToSort[2] + "" );<br />

www.it-ebooks.info<br />

35

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

Saved successfully!

Ooh no, something went wrong!