如何动态删除或重置javascript对象中的元素

时间:2012-03-13 06:58:37

标签: javascript jquery

我试图从其父对象中删除一个对象但没有成功...当我直接使用'delete'时它可以工作,但是当我在多个对象的循环中时,我无法让它工作?我在下面的$ .each循环中做错了什么:

<script>
 rc = { oc: { 'Amt': 30, 'mpA': 3000, 'ipP': 1, 'ppP': 12, 'mpP': 12000 },
        tb: { 'Amt': 2000, 'mpA': 100000, 'ipP': 1, 'ppP': 12, 'mpP': 12000 },
        bl: { 'Amt': 300, 'mpA': 100000, 'ipP': 1, 'ppP': 12, 'mpP': 12000 }    }

var carObj = {}
carObj['name'] = 'carObj';
console.log ( ' when created: carObj: ', carObj);

carObj['rc'] = rc; 
console.log ( 'when rc Loaded: carObj: ', carObj);

delete carObj['rc'];
console.log ( 'when rc deleted: carObj: ', carObj);

// up till here delete works as expected.
   // create two objects
var carObj1 = {}
var carObj2 = {}
   // load objects with the 'rc' object
carObj1['name'] = 'carObj1';
carObj1['rc'] = rc;
console.log ( 'when rc Loaded: carObj1: ', carObj1);

carObj2['name'] = 'carObj2';
carObj2['rc'] = rc;
console.log ( 'when rc Loaded: carObj2: ', carObj2);


// !!! Here is where delete doe not work.  i don;t get any errors, only rc not deleted from c
$.each([carObj1, carObj2], function (index, c){    
  console.log('before deleting rc', c);
 delete c[rc];
 console.log('After deleting rc', c);
});
</script>

2 个答案:

答案 0 :(得分:1)

您需要传递属性的名称,而不是对象。

delete c['rc'];

答案 1 :(得分:0)

尝试使用delete['rc']代替delete[rc]