jsÔõÑù±éÀú¹¤¾ßÖеÄÿ¸öÔªËØ
javascript ¹¤¾ß±éÀúÒªÁ죺for…in Ñ»·£º±éÀú×ÔÉí¼°ÔÐÍÁ´ÊôÐÔ¡£object.keys()£º·µ»Ø×ÔÉíÊôÐÔ¼üÊý×é¡£object.values()£º·µ»Ø×ÔÉíÊôÐÔÖµÊý×é¡£object.entries()£º·µ»Ø×ÔÉíÊôÐÔ¼üÖµ¶ÔÊý×éÊý×é¡£foreach()£º±éÀú¼üÖµ¶Ô²¢Ö´Ðлص÷º¯Êý¡£
ÔõÑù±éÀú JavaScript ¹¤¾ß
ÔÚ JavaScript ÖУ¬¹¤¾ßÊÇÒ»¸ö°üÀ¨¼üÖµ¶ÔµÄÊý¾Ý½á¹¹¡£±éÀú¹¤¾ßÉæ¼°µü´úÆäÊôÐÔ£¬²¢»á¼ûÿ¸öÊôÐԵļüºÍÖµ¡£
±éÀú¹¤¾ßµÄÒªÁì
Óм¸ÖÖÒªÁì¿ÉÒÔ±éÀú JavaScript ¹¤¾ß£º
1. for…in Ñ»·
for…in Ñ»·±éÀú¹¤¾ßµÄ×ÔÉí¿Éö¾ÙÊôÐÔ£¨°üÀ¨ÔÐÍÁ´ÉϵÄÊôÐÔ£©¡£
const person = { name: 'John', age: 30 }; for (const property in person) { console.log(`${property}: ${person[property]}`); }
µÇ¼ºó¸´ÖÆ
2. Object.keys()
Object.keys() ÒªÁì·µ»ØÒ»¸ö°üÀ¨¹¤¾ß×ÔÓÐÊôÐÔ¼üµÄÊý×é¡£
const keys = Object.keys(person); for (const key of keys) { console.log(`${key}: ${person[key]}`); }
µÇ¼ºó¸´ÖÆ
3. Object.values()
Object.values() ÒªÁì·µ»ØÒ»¸ö°üÀ¨¹¤¾ß×ÔÓÐÊôÐÔÖµµÄÊý×é¡£
const values = Object.values(person); for (const value of values) { console.log(value); }
µÇ¼ºó¸´ÖÆ
4. Object.entries()
Object.entries() ÒªÁì·µ»ØÒ»¸ö°üÀ¨¹¤¾ß×ÔÓÐÊôÐÔ¼üÖµ¶ÔÊý×éµÄÊý×é¡£
const entries = Object.entries(person); for (const [key, value] of entries) { console.log(`${key}: ${value}`); }
µÇ¼ºó¸´ÖÆ
5. forEach()
forEach() ÒªÁì±éÀú¹¤¾ßµÄÿһ¶Ô¼üÖµ£¬²¢Å²ÓÃÒ»¸öÌṩ¼üÖµ¶ÔµÄ»Øµ÷º¯Êý¡£
person.forEach((value, key) => { console.log(`${key}: ${value}`); });
µÇ¼ºó¸´ÖÆ
×¢ÖØÊÂÏî
ʹÓà for…in Ñ»·Ê±£¬ÒªÐ¡ÐÄÔÐÍÁ´ÉϵÄÊôÐÔ£¬ÓÉÓÚËüÃÇÒ²»á±»±éÀú¡£
ʹÓÃÆäËûÒªÁ죨Èç Object.keys()£©Ê±£¬Ö»±éÀú¹¤¾ßµÄ×ÔÉíÊôÐÔ¡£
Ñ¡Ôñ±éÀúÒªÁìÈ¡¾öÓÚËùÐèµÄÊý¾ÝºÍ²Ù×÷¡£
ÒÔÉϾÍÊÇjsÔõÑù±éÀú¹¤¾ßÖеÄÿ¸öÔªËصÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡