开发者

i cannot understand "sort function"

开发者 https://www.devze.com 2023-02-27 06:36 出处:网络
this questions maybe Easy for you .. but i am new in javascript i cannot understand this part in function

this questions maybe Easy for you .. but i am new in javascript

i cannot understand this part in function

kids.sort(function(n, m)

what n and m ?? and how i can understand this kind of functions

thsnks

<script>
function sortkids(e) {
     if (typeof e == "string") e = document.getElementById(e);
     var kids = [];
     for(var x = e.firstChild; x != null; x = x.nextSibling)
         if (x.nodeType == 1) kids.push(x);
     kids.sort(function(n, m) { 
                   var s = n.firstChild.data; 
            开发者_运维知识库       var t = m.firstChild.data;
                   if (s < t) return -1;    
                   else if (s > t) return 1;  
                   else return 0;           
               });

     for(var i = 0; i < kids.length; i++) e.appendChild(kids[i]);
}
</script>
<ul id="list"> 
<li>one<li>two<li>three<li>four <!-- items are not in alphabetical order -->
</ul>
<button onclick="sortkids('list')">Sort list</button>


.sort is doing the actual sorting for you, i.e. the shuffling around of items inside the array. What you need to tell .sort is how you want items sorted. You do this by supplying a function that takes two parameters and returns as information which of the two you consider "bigger" or "smaller" or whether both are equal (with the return values -1, 0 and 1).

.sort goes through the array, passing two elements at a time into your function asking "which one is bigger?", sorting the array based on the answer. It does this repeatedly until the array is sorted.


n and m will be elements from the array. The function will be called repeatedly, with different array elements to compare, and is expected to return a value saying whether n is less than, greater than, or equal to m. This lets sort do its job of sorting the array, even though sort doesn't know anything about the elements. All it needs to know, it gets from the function you pass in.

What that code is doing is putting DOM elements in an array, and then sorting it, which will only sort the elements in the array, not in the DOM. So then the bit at the end, doing the e.appendChild calls, is taking the sorted array and moving the elements in the DOM so they're in the right place. (It works because when you call appendChild with an element that's already in the DOM elsewhere, it gets moved; and appendChild always appends at the end.)

0

精彩评论

暂无评论...
验证码 换一张
取 消