Web Development with jQuery®

(Elliott) #1

(^158) ❘ CHAPTER 5 ITERATION OF ARRAYS AND OBJECTS
var madeArray = 1;
madeArray = $.makeArray(madeArray);
console.log('Transforming a number.');
console.log('Type: ' + typeof(madeArray));
console.log('Is Array? ' + (madeArray instanceof Array? 'yes' : 'no'));
console.log(madeArray);
}
);
The preceding code writes data to the JavaScript console like that shown in Figure 5-9.


FIGURE 5-9


In the script, the string The Beatles is assigned to the variable name. The variable name is passed
to makeArray(), and the result is assigned to the variable madeArray. Then, you check the typeof
of the object madeArray, which will be object now instead of string. The expression madeArray
instanceof Array will also report true, and then the content of madeArray is dumped to the console
for visual inspection.

The process is repeated for an object and a number, each time resulting in an array.


Finding a Value Within an Array


jQuery’s inArray() method works just like JavaScript’s indexOf() method. It returns the position of
an item within an array. If it is present, offset from zero, and if the item is not present, the function

http://www.it-ebooks.info

Free download pdf