JS:相关对象

时间:2010-08-12 19:18:13

标签: javascript oop

方案:   - 填写object1   - 将object1的内容复制到object2   - 从object1中删除元素

结果现在:   - object1和object2都删除了1个元素......?!

希望的结果:   - object1应该比object2

少1个元素

代码:

var object1 = new Object();
object1['key_one']   = 'value_1';
object1['key_two']   = 'value_2';
object1['key_three'] = 'value_3';
object1['key_four']  = 'value_4';
var object2 = new Object();
object2 = object1;
delete object1['key_three'];

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您的代码不进行任何复制。 object2只是一个新的空对象。试试这个:

var object1 = {
  key_one: "value_1",
  key_two: "value_2",
  key_three: "value_3",
  key_four: "value_4"
};
var object2 = {};
for (var prop in object1) {
  object2[prop] = object1[prop];
}
delete object1["key_three"];

现在object2object1的副本,但删除object1中的属性不会影响object2

希望这是有道理的。

答案 1 :(得分:0)

我并不认为object2曾经收到过object1的任何属性。你走在正确的轨道上,但你需要复制它们。

var object1 = new Object();
object1['key_one']   = 'value_1';
object1['key_two']   = 'value_2';
object1['key_three'] = 'value_3';
object1['key_four']  = 'value_4';

var object2 = new Object();
for(var i in object1){
    object2[i] =  object1[i];
}
delete object1['key_three'];