基於JS實現數字+字母+中文的混合排序方法_javascript技巧

來源:互聯網
上載者:User

在上篇文章給大家介紹了JavaScript sort數組排序方法和自我實現排序方法小結,用自己的方法實現了數字數組的排序。

當然,實際運用中,我還是會使用sort方法更加方便.但是,我上一篇博文,僅僅是實現了數字排序,而srot方法預設可是能給字母實現排序的哦!而My Code只能排序數字,看起來還是弱弱的.

所以,我得加上能排字母甚至中文的排序方法.

實現代碼

$(function(){var arr = ["Jack","Book","Fung",76,"Love","Mark","中國","china","phone","劉德華"];console.log('原數組');console.log(arr);console.log('for方法從小到大排序');console.log(arrSortMinToMax(arr));console.log('for方法從大到小排序');console.log(arrSortMaxToMin(arr));console.log('原數組');console.log(arr);});function arrMinNum(arr){var minNum = Infinity, index = -1,minVul = "";for (var i = 0; i < arr.length; i++) {if (typeof(arr[i]) == "string") {if (arr[i].charCodeAt()<minNum) {minNum = arr[i].charCodeAt();minVul = arr[i];index = i;}}else {if (arr[i]<minNum) {minNum = arr[i];minVul = arr[i]index = i;}}};return {"minNum":minVul,"index":index};}function arrSortMinToMax(arr){var arrNew = [];var arrOld = arr.concat();for (var i = 0; i < arr.length; i++) {arrNew.push(arrMinNum(arrOld).minNum);arrOld.splice(arrMinNum(arrOld).index,1)};return (arrNew);}function arrMaxNum(arr){var maxNum = -Infinity, index = -1,maxVul = "";for (var i = 0; i < arr.length; i++) {if (typeof(arr[i]) == "string") {if (arr[i].charCodeAt()>maxNum) {maxNum = arr[i].charCodeAt();maxVul = arr[i];index = i;}}else {if (arr[i]>maxNum) {maxNum = arr[i];maxVul = arr[i];index = i;}}};return {"maxNum":maxVul,"index":index};}function arrSortMaxToMin(arr){var arrNew = [];var arrOld = arr.slice(0);for (var i = 0; i < arr.length; i++) {arrNew.push(arrMaxNum(arrOld).maxNum);arrOld.splice(arrMaxNum(arrOld).index,1);};return (arrNew);}

運行截圖如下:

排序原理

如果是數字,則直接是數字進行比對

如果是字串,則使用charCodeAt()轉換成Unicode編碼進行排序.

Unicode 是 0 - 65535 之間的整數

其他說明

按照正常的排序邏輯,應該是:數字比一切字母都小,字母比一切中文都小,中文應該按照首字拼音的首字母排序.

我的這段代碼除了字母比一切中文都小這一條實現了,其他都沒有實現.

邏輯也應該可以實現,把數字字母中文分別找出來,數字跟數組進行比較,字母跟字母比較,中文跟中文比較,然後拼接數組

中文擷取首字的首字母可能稍微麻煩一點.

漢字居然可以直接比對的.

如上圖所示,張飛想要做老大是有道理的.JavaScript終於在千年之後為張飛正名,當年他就應該是做老大的!~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.