jsÖÐ×Ö·û´®ÔõÑùÅÅÐò
javascript×Ö·û´®ÅÅÐòÒªÁ죺ʹÓÃsort()ÒªÁì°´unicode´úÂëµãÉýÐòÅÅÐò¡£Ê¹ÓÃlocalecompare()ÒªÁìƾ֤ÓïÑÔÇéÐιæÔòÅÅÐò¡£½¨Éè×Ô½ç˵ÅÅÐòº¯Êý£¬Æ¾Ö¤Ìض¨±ê×¼£¨È糤¶È¡¢×Öĸ˳Ðò£©ÅÅÐò¡£
JavaScript ÖÐ×Ö·û´®ÅÅÐò
ÔÚ JavaScript ÖУ¬ÓÐÁ½ÖÖÖ÷ÒªµÄÒªÁì¿ÉÒÔ¶Ô×Ö·û´®¾ÙÐÐÅÅÐò£º
1. ʹÓùÌÓÐµÄ JavaScript ÒªÁì
sort()£º´ËÒªÁìͨ¹ý½«×Ö·û´®×ª»»Îª Unicode ´úÂëµã²¢Öð¸ö½ÏÁ¿ÕâЩ´úÂëµãÀ´¶Ô×Ö·û´®Êý×é¾ÙÐÐÅÅÐò¡£ËüÒÔÉýÐò·µ»ØÅÅÐòºóµÄÊý×é¡£
localeCompare()£º´ËÒªÁìƾ֤Ŀ½ñÓïÑÔÇéÐεÄÅÅÐò¹æÔò¶Ô×Ö·û´®¾ÙÐÐÅÅÐò¡£ËüÒÔ×Ö·û´®µÄÏà¶Ô˳Ðò·µ»ØÒ»¸öÊý×Ö¡£
ʾÀý£º
const strArray = ["Apple", "Banana", "Orange", "Grape", "Cherry"]; // ʹÓà sort() ¾ÙÐÐÉýÐòÅÅÐò strArray.sort(); console.log(strArray); // ["Apple", "Banana", "Cherry", "Grape", "Orange"] // ʹÓà localeCompare() ¾ÙÐнµÐòÅÅÐò strArray.sort((a, b) => b.localeCompare(a)); console.log(strArray); // ["Orange", "Grape", "Cherry", "Banana", "Apple"]
µÇ¼ºó¸´ÖÆ
2. ×Ô½ç˵ÅÅÐòº¯Êý
³ýÁËÄÚÖÃÒªÁìÖ®Í⣬»¹¿ÉÒÔ½¨Éè×Ô½ç˵ÅÅÐòº¯Êý£¬ÒÔƾ֤Ìض¨±ê×¼¶Ô×Ö·û´®¾ÙÐÐÅÅÐò¡£¿ÉÒÔʹÓà Array.prototype.sort() ÒªÁìÀ´×ª´ï×Ô½ç˵º¯Êý¡£
ʾÀý£º
°´×Ö·û´®³¤¶ÈÅÅÐò£º
const sortByLength = (a, b) => a.length - b.length; strArray.sort(sortByLength); console.log(strArray); // ["Apple", "Grape", "Cherry", "Banana", "Orange"]
µÇ¼ºó¸´ÖÆ
°´×Öĸ˳ÐòÄæÐòÅÅÐò£º
const sortByReverseAlphabetical = (a, b) => { const aLower = a.toLowerCase(); const bLower = b.toLowerCase(); return bLower.localeCompare(aLower); }; strArray.sort(sortByReverseAlphabetical); console.log(strArray); // ["Orange", "Grape", "Banana", "Cherry", "Apple"]
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÖÐ×Ö·û´®ÔõÑùÅÅÐòµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡