js数组sort() 的用法

关于数组的sort() 方法的具体使用说明

话不多说,直接上代码

<script>
        console.log("默认是把元素默认成字符串进行相互比较,从小到大");
        var arr = [11, 4, 13, 12, 5, 6];
        arr.sort();
        console.log(arr); // [11, 12, 13, 4, 5, 6]

        console.log("-------------------------------");
        console.log("这样是比较数值的大小,从小到大排序");
        var arr1 = [11, 14, 13, 2, 15, 20, 5, 3];
        arr1.sort((a, b) => a - b);
        console.log(arr1);  // [2, 3, 5, 11, 13, 14, 15, 20]
        console.log("或者写成:");
        var arr2 = [11, 14, 13, 2, 15, 20, 5, 3];
        arr2.sort(compare);
        function compare(a, b) {
            if (a > b) return 1;
            else if (a < b) return -1;
            else return 0;
        }
        console.log(arr2);  // [2, 3, 5, 11, 13, 14, 15, 20]

        console.log("-------------------------------");
        console.log("从大到小,反上亦然");
        var arr3 = [11, 14, 13, 2, 15, 20, 5, 3];
        arr3.sort((a, b) => b - a);
        console.log(arr3);  // [20, 15, 14, 13, 11, 5, 3, 2]
        console.log("或者写成:");
        var arr4 = [11, 14, 13, 2, 15, 20, 5, 3];
        arr4.sort(compare);
        function compare(a, b) {
            if (a > b) return -1;
            else if (a < b) return 1;
            else return 0;
        }
        console.log(arr4);  // [20, 15, 14, 13, 11, 5, 3, 2]
        console.log('---------------------------------');
        console.log("关于元素是字符串的sort()排序");
        console.log("JavaScript在做字符比较的时候,是根据字符对应的ASCII值来比较的。");
        var names = ['Ana', 'ana', 'john', 'John'];
        console.log(names.sort());
        console.log("如果不想区分大小写,可自定义:");
        names.sort(function (a, b) {
            if (a.toLowerCase() < b.toLowerCase()) {
                return -1
            }
            if (a.toLowerCase() > b.toLowerCase()) {
                return 1
            }
            return 0;
        });
        console.log(names);
    </script>
运行结果图如下


There’s nothing enlightened about shrinking.
退缩并非明智之举。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值