Presentation Tools
CocosCreator browser console
introduction
I believe that many small partners in the development are experiencing problems cited assigned. For example, the following figure:
I actually wanted to copy an array. However, changing the second array, the first array is also changed.
let array1 = [0];
let array2 = array1;
array2[0] = 2;
console.log(array1);
console.log(array2);
Console
fact, because for arrays (Object), the assignment only after changing the address point, both reference the same address. So a change, the other (reference the same address) will be with the change.
Analysis 1
First of all, we need to know five basic types: Undefined, Null, Boolean, Number, and String values are copied directly past.
The following two examples:
let test1 = true;
let test2 = test1;
test1 = false;
console.log(test1);
console.log(test2);
Console
let test1 = '001';
let test2 = test1;
test1 = '002';
console.log(test1);
console.log(test2);
Console
basic types of assignment, will open up a new memory, stored value. Both independent.
Analysis
So then, we need to understand that objects (arrays are objects) this thing. = Use only passing references.
such as:
let test1 = {
name: 'kuokuo'
};
let test2 = test1;
test2.name = 'notkuokuo';
console.log(test1);
console.log(test2);
Console
address or the address, so in fact it is a copy.
We can think of the array copy (a new new, old data will in turn assign the past) use a for loop.
However, the complexity of the object should be how to do it? Do not worry, there are ways!
let test1 = {
name: 'kuokuo'
};
let test2 = Object.assign({}, test1);
test1.name = 'changekuokuo';
console.log(test1);
console.log(test2);
Console
a copy of the object method of implementation.
but! ! !
Note that the second layer if the object. It does not work, only the one copy.
let test1 = {
name: 'kuokuo',
values: {
id: 6
}
};
let test2 = Object.assign({}, test1);
test1.name = 'changekuokuo';
test1.values.id = 8;
console.log(test1);
console.log(test2);
Console
name value has changed, but id still affected.
There are ways?
of course! My turn!
let test1 = {
name: 'kuokuo',
values: {
id: 6
}
};
let test2 = JSON.parse(JSON.stringify(test1));
test1.name = 'changekuokuo';
test1.values.id = 8;
console.log(test1);
console.log(test2);
Console
using the method of two copies of all conversions on JSON key-value.
Perfect yet?
No, this transformation can not be achieved on the function. How to do? I had a recursive assignment.
let deepClone = function (oldObj, newObj) {
for(let i in oldObj) {
if(typeof oldObj[i] === 'object') {
newObj[i] = {};
deepClone(oldObj[i], newObj[i]);
} else {
newObj[i] = oldObj[i];
}
};
return newObj;
};
let test1 = {
name: 'kuokuo',
values: {
id: 6,
age: 0
},
showAge: function() {
console.log('Age is ' + this.values.age);
}
};
let test2 = deepClone(test1, {});
test1.showAge();
test2.values.age = 18;
test2.showAge();
console.log(test1);
console.log(test2);
Console
O (∩_∩) O ~~
Small partners hope to gain something!