js-Two ways of copying arrays and objects

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:

Insert picture description here

The second type:
Insert picture description here

concat()The method is used to connect two or more arrays. In the second case, it concat(array1)returns array1a copy of Yes , and in the first case, it is array1the 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:
Insert picture description here

The second type:

Insert picture description here
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 PersonOnecopy the copy to PersonTwo.

3. Thinking

Insert picture description here

var PersonTwo = {}.concat(PersonOne);This will not work, because it concat()is an array method.
Insert picture description here

var array2 = Object.assign([], array1);This is feasible, because in a sense an array is also a kind of object.

Guess you like

Origin blog.csdn.net/Bob_ganxin/article/details/114165613
Recommended