1. 程式人生 > 其它 >2021.10.28(js字串與數字混合的字串排序要求先字元後數字)

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-2814:31:13

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