ÔõÑùÔÚjsÖбéÀúmap¹¤¾ß
javascript ÖбéÀú map ¹¤¾ßµÄÒªÁì°üÀ¨£ºÊ¹Óà foreach() ÒªÁ죬±éÀúÿ¸ö¼üÖµ¶Ô¡£Ê¹Óà for…of Ñ»·£¬±éÀú¼ü£¨»òÖµ£¬Ê¹Óà map.values() ±éÀúÆ÷£©¡£Ê¹Óà entries() ÒªÁ죬±éÀú¼üÖµ¶Ô¡£
ÔÚ JavaScript ÖбéÀú Map ¹¤¾ß
JavaScript µÄ Map ¹¤¾ßÊÇÒ»¸ö´æ´¢¼üÖµ¶ÔµÄÊý¾Ý½á¹¹£¬ËüÌṩÁËһЩҪÁìÀ´±éÀúÆäÄÚÈÝ¡£ÒÔÏÂÊÇ×î³£ÓõÄÒªÁ죺
ʹÓà forEach() ÒªÁì
forEach() ÒªÁì¿ÉÒÔ±éÀú Map ÖеÄÿ¸ö¼üÖµ¶Ô£¬²¢¶ÔËüÃÇÖ´Ðлص÷º¯Êý¡£»Øµ÷º¯ÊýÓ¦¸Ã½ÓÊÜÒÔϲÎÊý£º
value£º¼üÖµ¶ÔµÄÖµ
key£º¼üÖµ¶ÔµÄ¼ü
map£ºMap ¹¤¾ß×Ô¼º
ʾÀý£º
const map = new Map([ ['foo', 1], ['bar', 2], ['baz', 3], ]); map.forEach((value, key) => { console.log(`${key}: ${value}`); });
µÇ¼ºó¸´ÖÆ
Êä³ö£º
foo: 1 bar: 2 baz: 3
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
ʹÓà for…of Ñ»·
for…of Ñ»·¿ÉÒÔ±éÀú Map Öеļü¡£Òª±éÀúÖµ£¬¿ÉÒÔʹÓà map.values() ±éÀúÆ÷£º
for (let key of map.keys()) { console.log(key); } for (let value of map.values()) { console.log(value); }
µÇ¼ºó¸´ÖÆ
Êä³ö£º
foo bar baz 1 2 3
µÇ¼ºó¸´ÖÆ
ʹÓà entries() ÒªÁì
entries() ÒªÁì·µ»ØÒ»¸ö±éÀúÆ÷£¬ÆäÖаüÀ¨ Map ÖеļüÖµ¶Ô¡£
for (let entry of map.entries()) { const [key, value] = entry; console.log(`${key}: ${value}`); }
µÇ¼ºó¸´ÖÆ
Êä³ö£º
foo: 1 bar: 2 baz: 3
µÇ¼ºó¸´ÖÆ µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇÔõÑùÔÚjsÖбéÀúmap¹¤¾ßµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡