前端数据拷贝(浅拷贝、深拷贝)

浅拷贝

1 直接赋值

2 扩展运算符(...)

3 abject.assign()

Object.assign({}, obj);

4 slice和concat

slice 截取数组

concat 拼接数组

深拷贝

1 JSON.parse(JSON.stringify(待拷贝对象))

2 使用第三方库 Lodash

javascript 复制代码
const _ = require('lodash');

let obj = {
    name: 'demo',
    age: 26
}

let obj2 = _.cloneDeep(obj);
obj2.name = "demo_new";

console.log(obj); // {name: "demo", age: 26}
console.log(obj2); // {name: "demo_new", age: 26}

3 手写一个深拷贝

javascript 复制代码
function deepClone (obj) {
    if (typeof obj !== 'object' || obj == null) {
        return obj;
    }
    
    let deepCloneObj = Array.isArray(obj) ? [] : {}
    
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            deepCloneObj[key] = deepClone(obj[key]);
        }
    }
    
    return deepCloneObj;
}
相关推荐
a1117761 天前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得01 天前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
行走的陀螺仪1 天前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
We་ct1 天前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
2301_812731411 天前
CSS3笔记
前端·笔记·css3
ziblog1 天前
CSS3白云飘动动画特效
前端·css·css3
越努力越幸运5081 天前
CSS3学习之网格布局grid
前端·学习·css3
半斤鸡胗1 天前
css3基础
前端·css
ziblog1 天前
CSS3创意精美页面过渡动画效果
前端·css·css3
akangznl1 天前
第四章 初识css3
前端·css·css3·html5