Web Development with jQuery®

(Elliott) #1

(^156) ❘ CHAPTER 5 ITERATION OF ARRAYS AND OBJECTS
In the callback function passed to the map() method, a variable called track is created by increment-
ing the key’s value by one; it’s used as a counter for the track number. The callback function then
checks to see if track is less than 10 using a ternary expression. If it is, a leading zero is prepended
to the value; otherwise, no leading zero is prepended. This portion becomes the track number.
A single space is inserted between the track number and the song title, and the new array containing
song titles with track numbers prefi xed is assigned to the variable mappedSongs.
Finally, the array assigned to the mappedSongs variable is iterated using the each() method, and the
modifi ed song titles with track name prefi xes are appended as

  • elements to the
      element in
      the document. The result of the preceding example appears in Figure 5-8.


      FIGURE 5-8


      Array Utility Methods


      jQuery also provides a few utility methods that are useful for probing information from an array.
      The following sections briefl y cover each of jQuery’s utility methods:

      ➤ (^) $.makeArray(data)—Transforms any data into a true array
      ➤ (^) $.inArray(needle, haystack)—Finds the index associated with the fi rst occurrence of needle
      within the haystack
      ➤ (^) $.merge(first, second)—Merges two arrays together
      Most of jQuery’s array utility methods must be called directly, using the dollar sign dot function
      name, as you see documented in the preceding list. All the methods covered in this chapter are
      http://www.it-ebooks.info

  • Free download pdf