阅读:4931回复:1
js学习篇--数组按升序降序排列<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>数组数字大小排序</title> </head> <body> <p>让数组按照升序降序排列</p> <p>这里写个数组 var array=[1,80,4,33,21,55];</p> <p>升序输出:</p> <script type="text/javascript"> var array=[1,80,4,33,21,55]; array.sort(function (x,y) { return x-y; }); document.writeln(array); </script> <p>解释: x,y表示数组中的任意两个元素,若return > 0,则y前x;若reutrn < 0 ,则x前y后;当x=y时存在浏览器兼容。 简单来说:就是,x-y是按照从小到大排序,y-x是按照从大到小排序。</p> <p>顺手写个降序:</p> <script type="text/javascript"> var array=[1,80,4,33,21,55]; array.sort(function (x,y) { return y-x; }); document.writeln(array); </script> </body> </html> |
|
沙发#
发布于:2021-03-05 13:52
2、有需求是给数组的某个属性排序,用以下方法就可以实现了:
//升序 function compareAscSort(property){ return function(a,b){ var value1 = a[property]; var value2 = b[property]; return value1 - value2; } } //降序 function compareDescSort(property){ return function(a,b){ var value1 = a[property]; var value2 = b[property]; return value2 - value1; } } 使用示例: arr=[ //排序的数组 {name:'xx',age:12}, {name:'as',age:13}, {name:'sd',age:8} ]; asc_sort = arr.sort(compareAscSort("age")); //排序之后的数组 asc_sort=[ {name: "sd", age: 8}, {name: "xx", age: 12}, {name: "as", age: 13} ] ———————————————— 原文链接:https://blog.csdn.net/qq_29483485/article/details/85003814 |
|