×ðÁú¿­Ê±

jsÖÐÊý×éÔõÑùÈ¥ÖØ

ÔÚ javascript ÖУ¬ÓжàÖÖÒªÁì¿ÉÒÔ´ÓÊý×éÖÐɾ³ýÖظ´ÏʹÓà set Êý¾Ý½á¹¹£ºconst uniquearray = […new set(array)]ʹÓà array.prototype.filter(): const uniquearray = array.filter((item, index) => array.indexof(item) === index)ʹÓà array.prototype.reduce(): const uniquearray = ar

JavaScript Êý×éÈ¥Ö÷ÒªÁì

ÔÚ JavaScript ÖУ¬ÓжàÖÖÒªÁì¿ÉÒÔ´ÓÊý×éÖÐɾ³ýÖظ´Ï»ñµÃΨһԪËØ×é³ÉµÄÊý×é¡£

1. ʹÓà Set

Set ÊÇÒ»ÖÖÄÚÖõÄÊý¾Ý½á¹¹£¬Ëü¿ÉÒԴ洢Ψһֵ¡£¿ÉÒÔͨ¹ýÒÔÏ°취ʹÓà Set ¶ÔÊý×éÈ¥ÖØ£º

const array = [1, 2, 3, 1, 2, 3];
const uniqueArray = [...new Set(array)];

µÇ¼ºó¸´ÖÆ

uniqueArray ½«°üÀ¨ [1, 2, 3] µÄΨһֵ¡£

2. ʹÓà Array.prototype.filter()

filter() ÒªÁì¿ÉÒÔ¹ýÂËÊý×éÖеÄÔªËØ£¬½ö±£´æÖª×ãÖ¸¶¨Ìõ¼þµÄÔªËØ¡£¹ØÓÚÈ¥ÖØ£¬¿ÉÒÔʹÓÃÒÔÏÂÌõ¼þº¯Êý£º

const uniqueArray = array.filter((item, index) => array.indexOf(item) === index);

µÇ¼ºó¸´ÖÆ

¸ÃÌõ¼þº¯Êý¼ì²éÿ¸öÔªËØÊÇ·ñÊÇÊý×éÖеÚÒ»´Î·ºÆð¡£ÈôÊÇÊÇ£¬Ôò±£´æ¸ÃÔªËØ£¬²»È»ºöÂÔËü¡£

3. ʹÓà Array.prototype.reduce()

reduce() ÒªÁì¿ÉÒÔ½«Êý×éÖеÄÔªËØÀÛ»ýΪһ¸ö¼òµ¥Öµ¡£¹ØÓÚÈ¥ÖØ£¬¿ÉÒÔʹÓÃÒÔÏÂreduce º¯Êý£º

const uniqueArray = array.reduce((acc, item) => {
  if (!acc.includes(item)) {
    acc.push(item);
  }
  return acc;
}, []);

µÇ¼ºó¸´ÖÆ

¸Ãreduceº¯Êý½¨ÉèÒ»¸ö¿ÕÊý×é acc£¬È»ºó±éÀúÊý×éÔªËØ£¬ÈôÊÇ acc Öв»°üÀ¨Ä¿½ñÔªËØ item£¬Ôò½« item Ìí¼Óµ½ acc ÖС£

4. ʹÓÃÍâÑ­»·ºÍÄÚÑ­»·

ÕâÊÇ×îÖ±½Óµ«Ð§Âʽϵ͵ÄÒªÁ졣ʹÓÃÁ½¸öÑ­»·À´½ÏÁ¿Êý×éÖеÄÿ¸öÔªËØ£¬²¢É¾³ýÖظ´Ï

const uniqueArray = [];
for (let i = 0; i <p>ͨ¹ýʹÓÃÉÏÊöÒªÁìÖеÄÒ»ÖÖ£¬Äú¿ÉÒÔ´Ó JavaScript Êý×éÖÐÓÐÓõØɾ³ýÖظ´Ï»ñµÃÒ»¸ö°üÀ¨Î¨Ò»ÔªËصÄÊý×é¡£</p>

µÇ¼ºó¸´ÖÆ

ÒÔÉϾÍÊÇjsÖÐÊý×éÔõÑùÈ¥ÖصÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡

ÃâÔð˵Ã÷£ºÒÔÉÏչʾÄÚÈÝȪԴÓÚÏàÖúýÌå¡¢ÆóÒµ»ú¹¹¡¢ÍøÓÑÌṩ»òÍøÂçÍøÂçÕûÀí£¬°æȨÕùÒéÓë±¾Õ¾Î޹أ¬ÎÄÕÂÉæ¼°¿´·¨Óë¿´·¨²»´ú±í×ðÁú¿­Ê±ÂËÓÍ»úÍø¹Ù·½Ì¬¶È£¬Çë¶ÁÕß½ö×ö²Î¿¼¡£±¾ÎĽӴýתÔØ£¬×ªÔØÇë˵Ã÷À´ÓÉ¡£ÈôÄúÒÔΪ±¾ÎÄÇÖÕ¼ÁËÄúµÄ°æȨÐÅÏ¢£¬»òÄú·¢Ã÷¸ÃÄÚÈÝÓÐÈκÎÉæ¼°ÓÐÎ¥¹«µÂ¡¢Ã°·¸Ö´·¨µÈÎ¥·¨ÐÅÏ¢£¬ÇëÄúÁ¬Ã¦ÁªÏµ×ðÁú¿­Ê±ÊµÊ±ÐÞÕý»òɾ³ý¡£

Ïà¹ØÐÂÎÅ

ÁªÏµ×ðÁú¿­Ê±

18523999891

¿É΢ÐÅÔÚÏß×Éѯ

ÊÂÇéʱ¼ä£ºÖÜÒ»ÖÁÖÜÎ壬9:30-18:30£¬½ÚãåÈÕÐÝÏ¢

QR code
¡¾ÍøÕ¾µØͼ¡¿¡¾sitemap¡¿