Web Development with jQuery®

(Elliott) #1

Array Utility Methods (^) ❘ 157
documented in the Quick Reference that appears in Appendix I, “Utilities,” as well as Appendix C,
“Selecting, Traversing, and Filtering.” Appendix I contains utility methods, and Appendix C con-
tains jQuery methods that exist for fi ltering or traversing a selection.


Making an Array


jQuery’s makeArray() method does just what the name implies; it takes any data and transforms it
into a true array. The following example, Example 5-9, shows how a string, an object, or a number
can be made into an array using this method:

<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />
<title>$.makeArray()</title>
<script src='../jQuery.js'></script>
<script src='../jQueryUI.js'></script>
<script src='Example 5-9.js'></script>
</head>
<body>

</body>
</html>

The following JavaScript is included in the preceding markup document.


$(document).ready(
function()
{
var name = 'The Beatles';

var madeArray = $.makeArray(name);

console.log('Transforming a string.');
console.log('Type: ' + typeof(madeArray));
console.log('Is Array? ' + (madeArray instanceof Array? 'yes' : 'no'));
console.log(madeArray);

var madeArray = {
band1 : "The Beatles",
band2 : "Electric Light Orchestra",
band3 : "The Moody Blues",
band4 : "Radiohead"
};

madeArray = $.makeArray(madeArray);

console.log('Transforming an object.');
console.log('Type: ' + typeof(madeArray));
console.log('Is Array? ' + (madeArray instanceof Array? 'yes' : 'no'));
console.log(madeArray);

http://www.it-ebooks.info

Free download pdf