2021.10.28(js字符串与数字混合的字符串排序要求先字符后数字)

var result = [
            "eth0",
            "eth1",
            "eth10",
            "eth11",
            "eth12",
            "eth13",
            "eth14",
            "eth15",
            "eth2",
            "eth3",
            "eth4",
            "eth5",
            "eth6",
            "eth7",
            "eth8",
            "eth9",
        ]

result.sort(function(a,b){
             /*
             * return b-a; —> 降序排序
             * return a-b; —> 升序排列
             */
             return a-b;
        })
        console.log(result)

$(result).each(function (i, d) {
            $('<option>').html(d.toUpperCase()).val(d).appendTo($("#sel"));
        });

 

 搜索到的方法(能达到预期)

 

var list2 = []
        list2 = result.sort(function(a, b) {
          return a.localeCompare(b, 'zh-CN', { numeric: true })
        })
        console.log(list2)

 

 2021-10-28  14:31:13

var result = [
            "eth0",
            "eth1",
            "eth10",
            "eth11",
            "eth12",
            "eth13",
            "eth14",
            "eth15",
            "eth2",
            "eth3",
            "eth4",
            "eth5",
            "eth6",
            "eth7",
            "eth8",
            "eth9",
        ]

posted @ 2021-10-28 14:31  铁打的代码流水的bug  阅读(396)  评论(0)    收藏  举报