会改变原数组
<script>var arr = [4,6,2,9,3,5,6,14];var arr2 = [4,6,2,9,3,5,6,14];// 升序算法var a=arr.sort((a,b)=> {return a-b;})// 降序算法var b=arr2.sort((a,b)=> {return b-a;})console.log(...a);console.log(...arr);console.log(...b);</script>
封装示例
<!-- 封装示例 --><script>var students =[{"name":"zhang","age":"18","height":180},{"name":"li","age":"19","height":170},{"name":"wang","age":"14","height":200}]console.log(...students);// 升序function addOrder(arr,value){var res = arr.sort((a,b)=>{return a[value]-b[value];})return res;}// 降速function rdcOrder(arr,value){var res = arr.sort((a,b)=>{return b[value]-a[value];})return res;}// 按照age排序console.log(...addOrder(students,"age"));console.log(...rdcOrder(students,"age"));// 按照height排序console.log(...addOrder(students,"height"));console.log(...rdcOrder(students,"height"));</script>
