JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

7.8.3 sort()

var a = [1,2,3]; a.reverse().join() // => "3,2,1" and a is now [3,2,1]

7.8.3 sort()

Array.sort()sorts the elements of an array in place and returns the sorted array. When sort() is called with no arguments, it sorts the array elements in alphabetical order (temporarily converting them to strings to perform the comparison, if necessary):

var a = new Array("banana", "cherry", "apple"); a.sort(); var s = a.join(", "); // s == "apple, banana, cherry"

If an array contains undefined elements, they are sorted to the end of the array.

To sort an array into some order other than alphabetical, you must pass a comparison function as an argument to sort(). This function decides which of its two arguments should appear first in the sorted array. If the first argument should appear before the second, the comparison function should return a number less than zero. If the first argument should appear after the second in the sorted array, the function should return a number greater than zero. And if the two values are equivalent (i.e., if their order is irrelevant), the comparison function should return 0. So, for example, to sort array elements into numerical rather than alphabetical order, you might do this:

var a = [33, 4, 1111, 222]; a.sort(); // Alphabetical order: 1111, 222, 33, 4 a.sort(function(a,b) { // Numerical order: 4, 33, 222, 1111

7.8 Array Methods | 149

return a-b; // Returns < 0, 0, or > 0, depending on order }); a.sort(function(a,b) {return b-a}); // Reverse numerical order

Note the convenient use of unnamed function expressions in this code. Since the comparison functions are used only once, there is no need to give them names.

As another example of sorting array items, you might perform a case-insensitive alphabetical sort on an array of strings by passing a comparison function that converts both of its arguments to lowercase (with the toLowerCase() method) before comparing them:

a = ['ant', 'Bug', 'cat', 'Dog'] a.sort(); // case-sensitive sort: ['Bug','Dog','ant',cat'] a.sort(function(s,t) { // Case-insensitive sort

var a = s.toLowerCase(); var b = t.toLowerCase(); if (a < b) return -1; if (a > b) return 1; return 0;

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1