方案: - 填写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'];
我做错了什么?
答案 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"];
现在object2
是object1
的副本,但删除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'];