Home  >  Article  >  Web Front-end  >  A brief introduction to shallow copy and deep copy in js and how to implement them

A brief introduction to shallow copy and deep copy in js and how to implement them

不言
不言Original
2018-08-11 16:09:581823browse

This article brings you a brief introduction and implementation methods of shallow copy and deep copy in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First statement: What data type can be copied? Undoubtedly, arrays and objects [Array&Object]

Shallow copy:

* --- Method of copying data (shallow copy affects the original data)
* 1. Directly copy to variable //Shallow copy
* 2.Object.assign() //Object shallow copy
* 3.Array.prototype.concat() //Array shallow copy
* 4. Array.prototype.slice() //Array shallow copy

Deep copy:

Method 1:

//无嵌套对象或者数组浅拷贝
function simpleDeepClone(target){
       return JSON.parse(JSON.stringify(target));
}

Method 2:

//嵌套对象或者数组深拷贝
//定义检测数据类型的函数
function checkType(target) {
    return Object.prototype.toString.call(target).slice(8, -1);
}

//实现深度拷贝
function clone(target) {
    //判断拷贝的数据类型
    let result, targetType = checkType(target);
    if (targetType === 'Object') {
        result = {};
    } else if (targetType === 'Array') {
        result = [];
    } else {
        return target;
    }
    //遍历目标数据
    for (let i in target) {
        //获取数据对象的每一个值
        let value = target[i];
        //判断目标结构里面是否存在对象/数组
        if (checkType(value) === 'Object' || checkType(value) === 'Array') {
            //继续遍历
            result[i] = clone(value);
        } else { //获取到的value值是基本的数据类型或者函数
            result[i] = value;
        }
    }
    return result;
}

Related recommendations:

jQuery’s $.extend shallow copy and deep copy example analysis

js implementation of deep and shallow copy methods

The above is the detailed content of A brief introduction to shallow copy and deep copy in js and how to implement them. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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