Article Directory
1. Two kinds of copy of array
//第一种
var array1 = ["1", "2", "3"];
var array2 = array1;
console.log(array2);
array1[0] = "4";
console.log(array2)
//第二种
var array1 = ["1", "2", "3"];
var array2 = [ ].concat(array1);
console.log(array2);
array1[0] = "4";
console.log(array2)
Operation results The
first type:
The second type:
concat()
The method is used to connect two or more arrays. In the second case, it concat(array1)
returns array1
a copy of Yes , and in the first case, it is array1
the address, similar to a pointer. So the second way to change array1 will not change array2.
2. Two kinds of copying of objects
//第一种
var PersonOne = {
name: "bob", sex: "man", age: "99"};
var PersonTwo = PersonOne;
console.log(PersonTwo);
PersonOne.age = "40";
console.log(PersonTwo)
//第二种
var PersonOne = {
name: "bob", sex: "man", age: "99"};
var PersonTwo = Object.assign({
}, PersonOne);
//var PersonTwo;
//Object.assign(PersonTwo, PersonOne);
//也可以
console.log(PersonTwo);
PersonOne.age = "40";
console.log(PersonTwo)
Operation results The
first type:
The second type:
Object.assign()
The method is used to copy the values of all enumerable properties from one or more source objects to the target object, and it will return the target object. This sets the target object to {}
be able to PersonOne
copy the copy to PersonTwo
.
3. Thinking
var PersonTwo = {}.concat(PersonOne);
This will not work, because it concat()
is an array method.
var array2 = Object.assign([], array1);
This is feasible, because in a sense an array is also a kind of object.