Bug Tracker

Ticket #5686: map_example.html

File map_example.html, 1.6 KB (added by robertsosinski, 10 years ago)
Line 
1<!DOCTYPE html>
2
3<html>
4<head>
5  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
6</head>
7
8<body>
9  <div>a</div>
10  <div>b</div>
11  <div>c</div>
12 
13  <script type="text/javascript">
14    // $#each and $#map both take functions with (index, element)
15    // and they both reassign "this" to the current element
16   
17    var selector = "div:not('_firebugConsole')";
18   
19    console.log("--- $#each---");
20   
21    $(selector).each(function(index, element) {
22        console.log("letter " + element.innerHTML);
23        console.log("letter " + this.innerHTML);
24    });
25   
26    console.log("--- $#map---");
27   
28    $(selector).map(function(index, element) {
29        console.log("letter " + this.innerHTML);
30        console.log("letter " + element.innerHTML);
31    });
32   
33    // $.each also takes a function with (index, element)
34    // and reassignes "this" to the current element.
35    // However $.map instead takes (element, index)
36    // and "this" is not reassigned to the element
37   
38    var array = ["a", "b", "c"];
39   
40    console.log("--- $.each---");
41   
42    $.each(array, function(index, element) {
43      console.log("letter " + element);
44      console.log("letter " + this);
45    });
46   
47    console.log("--- $.map---");
48   
49    $.map(array, function(index, element) {
50                     // ^ ERROR: $.map takes (element, index)
51      console.log("letter " + element); // < will print the index instead of the letter
52      console.log("letter " + this); // < will print [object Window] instead of the letter
53    });
54  </script>
55</body>
56</html>