Home > Web Front-end > JS Tutorial > How to copy an object in js? (Picture and text tutorial)

How to copy an object in js? (Picture and text tutorial)

亚连
Release: 2018-05-18 16:21:30
Original
1685 people have browsed it

The following is what I have compiled for you on how to copy an object in js. Interested students can take a look.

Method 1:

Traverse the properties of the original object and assign them to a new object.

//深复制对象方法    
var cloneObj = function (obj) {  
    var newObj = {};  
    if (obj instanceof Array) {  
        newObj = [];  
    }  
    for (var key in obj) {  
        var val = obj[key];  
        //newObj[key] = typeof val === 'object' ? arguments.callee(val) : val; //arguments.callee 在哪一个函数中运行,它就代表哪个函数, 一般用在匿名函数中。  
        newObj[key] = typeof val === 'object' ? cloneObj(val): val;  
    }  
    return newObj;  
};  
//测试    
var obj = {a:function(){console.log(this.b.c)},b:{c:1}},//设置一个对象  
newObj = cloneObj(obj);//复制对象  
newObj.b.c=2;//给新对象赋新值  
obj.a();//1,不受影响  
newObj.a();//2
Copy after login

Method 2:

Serialize the object and then parse it back. If there is a function in the object, it cannot be copied correctly

var obj = {a:1,b:2}  
var newObj = JSON.parse(JSON.stringify(obj));  
newObj.a=3;  
console.log(obj);  
console.log(newObj);
Copy after login

Method 3:

For the method of array object, use the array method to concat an empty array

var a=[1,2,3];  
var b=a;  
var c=[].concat(a);  
a.push(4);  
console.log(b);  
console.log(c);
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JS retains two decimal places for input number verification code

JS retains one digit and moves it backward Unless the number

JS refresh page method summary

The above is the detailed content of How to copy an object in js? (Picture and text tutorial). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template