jsÔõôɾ³ý¹¤¾ß
javascript ÖÐɾ³ý¹¤¾ßµÄÒªÁì°üÀ¨£ºÊ¹Óà delete Òªº¦×ÖÖ±½Óɾ³ýÕû¸ö¹¤¾ß¡£Ê¹Óà delete Òªº¦×Öºó¸úÊôÐÔÃû³Æɾ³ýÌض¨ÊôÐÔ¡£Ê¹Óà object.keys() ºÍ foreach() µü´ú²¢É¾³ýËùÓÐÊôÐÔ¡£¹ØÓÚǶÌ×¹¤¾ß£¬Ê¹Óõݹéɾ³ýÌض¨ÊôÐÔ£¬Í¨¹ý deleteproperty() º¯ÊýʵÏÖ¡£
ÔõÑùÔÚ JavaScript ÖÐɾ³ý¹¤¾ß
Ö±½Óɾ³ýÕû¸ö¹¤¾ß
×î¼òÆÓµÄÒªÁìÊÇʹÓà delete Òªº¦×Ö£º
const myObject = { name: "John", age: 30 }; delete myObject;
µÇ¼ºó¸´ÖÆ
Õ⽫Íêȫɾ³ý myObject ¹¤¾ß¡£
ɾ³ý¹¤¾ßÖеÄÌض¨ÊôÐÔ
Òª½öɾ³ý¹¤¾ßÖеÄÌض¨ÊôÐÔ£¬¿ÉÒÔʹÓà delete Òªº¦×Öºó¸úÊôÐÔÃû³Æ£º
const myObject = { name: "John", age: 30 }; delete myObject.age;
µÇ¼ºó¸´ÖÆ
ʹÓà Object.keys() ºÍ forEach()
ÈôÊÇÒªµü´ú¹¤¾ß²¢Öð¸öɾ³ýÊôÐÔ£¬¿ÉÒÔʹÓà Object.keys() ºÍ forEach()£º
const myObject = { name: "John", age: 30, city: "New York" }; Object.keys(myObject).forEach((key) => { delete myObject[key]; });
µÇ¼ºó¸´ÖÆ
Õ⽫ɾ³ý myObject ÖеÄËùÓÐÊôÐÔ¡£
ɾ³ýǶÌ×¹¤¾ßµÄÊôÐÔ
¹ØÓÚǶÌ×¹¤¾ß£¬¿ÉÒÔʹÓõݹéÀ´É¾³ýÌض¨ÊôÐÔ¡£ÀýÈ磬Ҫɾ³ý myObject.address.street ÊôÐÔ£º
const myObject = { name: "John", age: 30, address: { street: "Main Street", city: "New York", }, }; function deleteProperty(object, path) { const parts = path.split("."); if (parts.length === 1) { delete object[parts[0]]; } else { deleteProperty(object[parts[0]], parts.slice(1).join(".")); } } deleteProperty(myObject, "address.street");
µÇ¼ºó¸´ÖÆ
×¢ÖØÊÂÏî
ɾ³ý¹¤¾ß»òÊôÐÔºó£¬ËüÃǽ«²»ÔÙ¿ÉÓá£
delete Òªº¦×Ö²»»áÓ°Ï칤¾ßÔÐÍÁ´£¬Òò´ËËü²»»áɾ³ý´ÓÔÐͼÌÐøµÄÊôÐÔ¡£
ÔÚÑÏ¿áģʽÏ£¬Ê¹Óà delete ¶Ô·Ç¿ÉÉèÖÃÊôÐÔ£¨Èç const ±äÁ¿£©ÎÞЧ¡£
ÒÔÉϾÍÊÇjsÔõôɾ³ý¹¤¾ßµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡