delete运算符可以删除对象的属性,但是仅仅是断开了属性和宿主对象的联系,而不会去操作被删除属性的属性值,所以就需要彻底删除的出现
function myDelete(obj,propertyName){ if(typeof obj[propertyName]==="object"){ for(var i in obj[propertyName]){ myDelete(obj[propertyName],i); } delete obj[propertyName]; }else{ delete obj[propertyName]; } }
测试代码:
var myObj={x:{x11:2,x12:{x21:2,x22:3}},y:{y11:2,y12:{y21:2,y22:3}}}; var x=myObj.x; myDelete(myObj,"x"); console.log("-----------") console.log(x);//Object {} console.log(myObj.x);//undefined