jsÔõôɾ³ýÊý×éÖеÄijһÏî
ÓÐÈýÖÖ´Ó javascript Êý×éÖÐɾ³ýÒ»ÏîµÄÒªÁ죺ʹÓà splice() ÒªÁìÔÚÖ¸¶¨Î»ÖÃɾ³ýÏʹÓà filter() ÒªÁ콨ÉèÐÂÊý×飬½ö°üÀ¨ÇкÏÌõ¼þµÄÏʹÓà slice() ºÍ concat() ÒªÁ츴ÖÆËùÐèÏîµ½ÐÂÊý×éÖС£
ÔõÑùÔÚJavaScriptÖдÓÊý×éÖÐɾ³ýÒ»Ïî
ÒªÁìÒ»£ºÊ¹ÓÃsplice()ÒªÁì
splice()ÒªÁì¿ÉÒÔɾ³ýÊý×éÖÐÖ¸¶¨Î»ÖõÄÏ²¢¿Éƾ֤ÐèÒª²åÈëеÄÏî¡£Óï·¨ÈçÏ£º
array.splice(start, deleteCount, ...items)
µÇ¼ºó¸´ÖÆ
ÆäÖУº
start£ºÒª×îÏÈɾ³ýµÄÏîµÄË÷Òý
deleteCount£ºÒªÉ¾³ýµÄÏîµÄÊýÄ¿
items£º¿ÉÑ¡²ÎÊý£¬Òª²åÈëµ½×îÏÈλÖúóµÄÐÂÏî
ʾÀý£º
const arr = [1, 2, 3, 4, 5]; arr.splice(2, 1); // ɾ³ýµÚ3ÏË÷ÒýΪ2£© console.log(arr); // Êä³ö£º[1, 2, 4, 5]
µÇ¼ºó¸´ÖÆ
ÒªÁì¶þ£ºÊ¹ÓÃfilter()ÒªÁì
filter()ÒªÁ콨ÉèÒ»¸öеÄÊý×飬ÆäÖÐÖ»°üÀ¨Í¨¹ý¸ø¶¨²âÊÔÌõ¼þµÄÏî¡£ÎÒÃÇ¿ÉÒÔʹÓÃËüÀ´ÌÞ³ý²»ÐèÒªµÄÏî¡£Óï·¨ÈçÏ£º
array.filter(callback(currentValue, index, array))
µÇ¼ºó¸´ÖÆ
ÆäÖУº
callback£ºÒ»¸öº¯Êý£¬Ëü·µ»ØÒ»¸ö²¼¶ûÖµ£¬Ö¸Ê¾Òª»ò²»Òª±£´æ¸ÃÏî
ʾÀý£º
const arr = [1, 2, 3, 4, 5]; const newArr = arr.filter((item) => item !== 3); // ɨ³ýֵΪ3µÄÏî console.log(newArr); // Êä³ö£º[1, 2, 4, 5]
µÇ¼ºó¸´ÖÆ
ÒªÁìÈý£ºÊ¹ÓÃslice()ºÍconcat()ÒªÁì
slice()ÒªÁ콨ÉèÒ»¸öÐÂÊý×飬ÆäÖаüÀ¨ÔʼÊý×éÖÐÖ¸¶¨¹æÄ£ÄÚµÄÏî¡£ÎÒÃÇ¿ÉÒÔ½«ÆäÓëconcat()ÒªÁìÍŽáʹÓ㬽«ËùÐèµÄÏÖƵ½ÐÂÊý×éÖС£Óï·¨ÈçÏ£º
const newArr = arr.slice(0, start).concat(arr.slice(end + 1));
µÇ¼ºó¸´ÖÆ
ÆäÖУº
start£ºÒª×îÏȸ´ÖƵÄË÷Òý
end£ºÒª×èÖ¹¸´ÖƵÄË÷Òý
ʾÀý£º
const arr = [1, 2, 3, 4, 5]; const newArr = arr.slice(0, 2).concat(arr.slice(3)); // ɾ³ýµÚ3ÏË÷ÒýΪ2£© console.log(newArr); // Êä³ö£º[1, 2, 4, 5]
µÇ¼ºó¸´ÖÆ
ÒÔÉϾÍÊÇjsÔõôɾ³ýÊý×éÖеÄijһÏîµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡