在这段代码中,我将array1的副本分配给变量array2,但是当我更改array1时,它会更改array2。为什么会这样?
var array1 = [1, 2, 3, 4, 5];
var array2 = array1;
array1.pop();
console.log("array1: " + array1 + "\narray2: " + array2);
//output: array1: 1,2,3,4
// array2: 1,2,3,4
由于数组是对象,我用一个对象测试了相同的概念并得到了相同的结果。我从原始对象中删除了一个属性,并从另一个对象的副本中删除了相同的属性。引擎盖下发生了什么?
var obj1 = {name: "object", day: "Tuesday", color: "yellow"};
var obj2 = obj1;
console.log("BEFORE DELETE:");
console.log("obj1 properties:");
for(var prop in obj1) {
console.log(prop);
}
console.log("obj2 properties:");
for(var prop in obj2) {
console.log(prop);
}
delete obj1.color; //delete only from obj1
console.log("AFTER DELETE:");
console.log("obj1 properties:");
for(var prop in obj1) {
console.log(prop);
}
console.log("obj2 properties:");
for(var prop in obj2) {
console.log(prop);
}
//output: BEFORE DELETE:
// obj1 properties:
// name
// day
// color
// obj2 properties:
// name
// day
// color
// AFTER DELETE:
// obj1 properties:
// name
// day
// obj2 properties:
// name
// day
令人困惑,因为我希望它的行为与此相同:
var cow = "moo";
var calf = cow;
console.log("BEFORE CHANGE:");
console.log("cow: " + cow); //prints "moo"
console.log("calf: " + calf); //prints "moo"
cow = "oink";
console.log("AFTER CHANGE:");
console.log("cow: " + cow); //prints "oink"
console.log("calf: " + calf); //still prints "moo"