js 的数组排序函数研究 sort(),reverse()
js 的 sort()函数用来做数组排序非常有效且简单,以下是几种常用的场景.
<script> var a = ['b','d','c','a','f','e']; var b = a.sort(); console.log(b); //b = ['a','b','c','d','e','f']; </script>
当然,既然能以字典序排序,自然也能以大小排序.
<script> var c = [9,4,5,2,3,1,8,7,6]; var d = a.sort(function(a,b){ return a-b; }); console.log(d); //b = [1,2,3,4,5,6,7,8,9]; var e = a.sort(function(a,b){ return b-a; }); console.log(e); //e = [9,8,7,6,5,4,3,2,1]; </script>
这就是天然的冒泡排序了,超级简单有木有?
reverse() 函数可以将数组倒序排列,通常我们可以用来倒序排列数据,可以缓解后端数据库的计算压力.
<script> var a = ["s","g","a"]; console.log(a.reverse()); // ["a","g","s"]; </script>