js 中的sort方法实现数组排序

sort(方法函数)方法使数组中的元素按照一定的顺序排列。

sort方法参数可写方法函数来实现想要的排序效果

下面的是数组是对数组就行排序:

       function sortUp(a, b) {
            return a - b; //升序
        }

        function sortDown(a, b) {
            return b - a; //降序
        }
        var myarr = [100, 10, 25, 6, 54, 6]
        console.log(myarr.sort(sortUp));
        console.log(myarr.sort(sortDown));

注意: 该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下: 

  •   若返回值<=-1,则表示 A 在排序后的序列中出现在 B 之前。
  •   若返回值>-1 && <1,则表示 A 和 B 具有相同的排序顺序。
  •   若返回值>=1,则表示 A 在排序后的序列中出现在 B 之后。

以上是实现对数组的简单排序,上面方法理解了,那对属性值是怎么排序 的呢? sort方法也可以实现!!!

       function comp(index) {
            return (a, b) => a[index] - b[index];
            // return function(a, b) {
            //     return a[index] - b[index];
            // }与上面写法等价
        }

        var myarr = [{
            name: '迪迦',
            money: 20,
        }, {
            name: '赛罗',
            money: 25,
        }, {
            name: '泰罗',
            money: 11,
        }, {
            name: '塞斯',
            money: 30
        }]
        console.log(myarr.sort(comp('money'))); //按照money就行升序

原创文章 24 获赞 13 访问量 1343

猜你喜欢

转载自blog.csdn.net/qq_44755188/article/details/105927620