jsÖÐÔõÑù±éÀúÊý×é
ÔÚ javascript ÖбéÀúÊý×飬ÓÐÎåÖÖ³£ÓÃÒªÁ죺for Ñ»·£ºÖð¸ö±éÀúÊý×éÔªËØ¡£foreach()£ºÌṩһ¸ö»Øµ÷º¯Êý£¬¶Ôÿ¸öÔªËØŲÓá£map()£º½¨ÉèÒ»¸öÐÂÊý×飬ÆäÖаüÀ¨¶Ôÿ¸öÔªËØÓ¦Óú¯ÊýµÄЧ¹û¡£filter()£º½¨ÉèÒ»¸öÐÂÊý×飬ÆäÖаüÀ¨Í¨¹ýº¯Êý²âÊÔµÄÔªËØ¡£reduce()£º½«Êý×éÔªËØÀÛ»ýµ½µ¥¸öÖµ¡£
ÔõÑùÔÚ JavaScript ÖбéÀúÊý×é
ÔÚ JavaScript ÖУ¬±éÀúÊý×éÓжàÖÖÒªÁ죬ÿÖÖÒªÁ춼ÓÐÆäÌض¨µÄÓÃÀý¡£ÒÔÏÂÊdz£ÓõıéÀúÊý×éµÄÒªÁ죺
for Ñ»·
ÕâÊÇ×î»ù±¾µÄ±éÀúÊý×éµÄÒªÁ죬ËüʹÓÃÒ»¸ö for Ñ»·Öð¸ö±éÀúÊý×éÖеÄÔªËØ¡£
const numbers = [1, 2, 3, 4, 5]; for (let i = 0; i <p><strong>forEach</strong></p><p>forEach() ÒªÁìÊÇÒ»¸ö¸ü¾«Á·µÄ±éÀúÊý×éµÄÒªÁì¡£ËüÌṩһ¸ö»Øµ÷º¯Êý£¬¸Ãº¯Êý½«¶ÔÊý×éÖеÄÿ¸öÔªËØŲÓá£</p><pre class="brush:php;toolbar:false">const numbers = [1, 2, 3, 4, 5]; numbers.forEach((number) => { console.log(number); });
µÇ¼ºó¸´ÖÆ
map
map() ÒªÁ콨ÉèÒ»¸öÐÂÊý×飬ÆäÖаüÀ¨¶ÔÊý×éÖÐÿ¸öÔªËØÓ¦Óøø¶¨º¯ÊýµÄЧ¹û¡£
const numbers = [1, 2, 3, 4, 5]; const squaredNumbers = numbers.map((number) => { return number * number; }); console.log(squaredNumbers); // [1, 4, 9, 16, 25]
µÇ¼ºó¸´ÖÆ
filter
filter() ÒªÁ콨ÉèÒ»¸öÐÂÊý×飬ÆäÖаüÀ¨Í¨¹ý¸ø¶¨º¯ÊýµÄ²âÊÔµÄÊý×éÔªËØ¡£
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter((number) => { return number % 2 === 0; }); console.log(evenNumbers); // [2, 4]
µÇ¼ºó¸´ÖÆ
reduce
reduce() ÒªÁ콫Êý×éÔªËØÀÛ»ýµ½µ¥¸öÖµ¡£ËüÌṩһ¸ö»Øµ÷º¯Êý£¬¸Ãº¯ÊýÓÐÁ½¸ö²ÎÊý£ºµÚÒ»¸ö²ÎÊýÊÇÀÛ»ýÖµ£¬µÚ¶þ¸ö²ÎÊýÊÇÄ¿½ñÔªËØ¡£
const numbers = [1, 2, 3, 4, 5]; const sum = numbers.reduce((accumulator, number) => { return accumulator + number; }, 0); console.log(sum); // 15
µÇ¼ºó¸´ÖÆ
ÄÄÖÖ±éÀúÒªÁì×îÊʺÏÄúµÄÌض¨ÓÃÀýÈ¡¾öÓÚÄúµÄÐèÇó¡£¹ØÓÚ¼òÆӵıéÀú£¬for Ñ»·»ò forEach() ÒªÁì¾Í×ã¹»ÁË¡£¹ØÓÚ¸üÖØ´óµÄ±éÀú²Ù×÷£¬ÀýÈçÓ³Éä¡¢¹ýÂË»ò¹éÔ¼£¬Ê¹Óà map()¡¢filter() »ò reduce() ÒªÁì¸üΪºÏÊÊ¡£
ÒÔÉϾÍÊÇjsÖÐÔõÑù±éÀúÊý×éµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡