Javascript 数组排序详解
如果你接触javascript有一段时间了,你肯定知道数组排序函数sort,sort是array原型中的一个方法,即array.prototype.sort(),sort(compareFunction),其中compareFunction是一个比较函数,下面我们看看来自MozillaMDN的一段描述:
IfcompareFunctionisnotsupplied,elementsaresortedbyconvertingthemtostringsandcomparingstringsinlexicographic(“dictionary”or“telephonebook,”notnumerical)order.Forexample,“80″comesbefore“9″inlexicographicorder,butinanumericsort9comesbefore80.
下面看些简单的例子:
//Output[1,2,3] console.log([3,2,1].sort());
//Output["a","b","c"] console.log(["c","b","a"].sort());
//Output[1,2,"a","b"] console.log(["b",2,"a",1].sort());