jsÖÐmapº¯ÊýÓ÷¨
map º¯ÊýÔÚ javascript Öн«Êý×éÖеÄÔªËØÓ³Éäµ½ÐÂÔªËØ£¬Í¨¹ý¸ø¶¨µÄº¯Êýת»»ÔʼÊý×éÖеÄÿ¸öÔªËØ£¬²¢·µ»ØÒ»¸ö°üÀ¨Ó³ÉäºóÔªËصÄÐÂÊý×é¡£
Map º¯ÊýÔÚ JavaScript ÖеÄÓ÷¨
Map º¯ÊýÊÇÒ»Öָ߽׺¯Êý£¬Ëü½«Êý×éÖеÄÿ¸öÔªËØÓ³Éäµ½Ò»¸öÐÂÔªËØ¡£ÐÂÊý×éÖеÄÔªËØÊÇͨ¹ý½«¸ø¶¨µÄº¯ÊýÓ¦ÓÃÓÚÔʼÊý×éÖеÄÿ¸öÔªËضø»ñµÃµÄ¡£
Óï·¨£º
map(callbackFn, thisArg)
µÇ¼ºó¸´ÖÆ
²ÎÊý£º
callbackFn£º Ò»¸öº¯Êý£¬ÓÃÓÚ½«ÔʼÊý×éÖеÄÿ¸öÔªËØת»»ÎªÐÂÔªËØ¡£Ëü½ÓÊÜÈý¸ö²ÎÊý£º
currentValue£º ÕýÔÚ´¦ÀíµÄÄ¿½ñÔªËØ¡£
index£º Ä¿½ñÔªËØÔÚÔʼÊý×éÖеÄË÷Òý¡£
array£º ÔʼÊý×é¡£
thisArg£¨¿ÉÑ¡£©£º ÓÃÓÚ°ó¶¨ this Öµ£¨ÉÏÏÂÎĵÄÖ¸Õ룩µÄ¿ÉÑ¡¹¤¾ß¡£ÈôÊÇδÌṩ£¬Ôò this ½«Ö¸ÏòÈ«¾Ö¹¤¾ß¡£
·µ»ØÖµ£º
Ò»¸öÐÂÊý×飬ÆäÖаüÀ¨Ó³ÉäºóµÄÔªËØ¡£
Ó÷¨£º
Map º¯Êýͨ³£ÓëÊý×éÒªÁì forEach ºÍ filter Ò»ÆðʹÓá£Ëü¿ÉÓÃÓÚ½¨ÉèÐÂÊý×飬ÆäÖаüÀ¨ÔʼÊý×éÖÐÔªËصÄת»»°æ±¾¡£
// ½¨ÉèÒ»¸öÊý×é const numbers = [1, 2, 3, 4, 5]; // ʹÓà map º¯Êý½«Ã¿¸öÔªËØƽ·½ const squares = numbers.map((num) => num * num); // Êä³öЧ¹û console.log(squares); // [1, 4, 9, 16, 25]
µÇ¼ºó¸´ÖÆ
ÔÚÒÔÉÏʾÀýÖУ¬map º¯Êý½« numbers Êý×éÖеÄÿ¸öÔªËØƽ·½£¬²¢½«Ð§¹û´æ´¢ÔÚ squares Êý×éÖС£
ÆäËûÓ÷¨£º
ÐÞ¸ÄÊý×éÔªËØ£º map º¯Êý¿ÉÓÃÓÚÐÞ¸ÄÊý×éÖеÄÔªËØ£¬¶øÎÞÐ轨ÉèÐÂÊý×é¡£
¹ýÂËÊý×éÔªËØ£º map º¯Êý¿ÉÓë filter º¯ÊýÍŽáʹÓã¬ÒÔ¹ýÂËÊý×éÖеÄÔªËز¢½ö·µ»ØÖª×ãÌض¨Ìõ¼þµÄÔªËØ¡£
½¨É蹤¾ß£º map º¯Êý¿ÉÓÃÓÚ´ÓÊý×齨É蹤¾ß£¬ÆäÖÐË÷ÒýÓÃ×÷¼ü£¬ÔªËØÓÃ×÷Öµ¡£
ÒÔÉϾÍÊÇjsÖÐmapº¯ÊýÓ÷¨µÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡