首页 > 其他分享 >js 封装一个实现数组、对象深拷贝的函数

js 封装一个实现数组、对象深拷贝的函数

时间:2022-10-13 23:44:22浏览次数:56  
标签:isArray object return Object 封装 js deepCopy obj 拷贝

HTML代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>深拷贝</title>
</head>

<body>
    <script>
        function deepCopy(obj) {
            // 1.
            // let res = Array.isArray(obj) ? [] : {}
            // for (const [k, v] of Object.entries(obj)) {
            //     res[k] = typeof v === "object" ? deepCopy(v) : v
            // }
            // return res

            // 2.简写
            // return Object.entries(obj).reduce((t, cur, index, arr) => {
            //     let [k, v] = cur
            //     t[k] = typeof v === "object" ? deepCopy(v) : v
            //     return t
            // }, Array.isArray(obj) ? [] : {})

            // 3.一行
            // return Object.entries(obj).reduce((t, [k, v]) => (t[k] = typeof v === "object" ? deepCopy(v) : v, t), Array.isArray(obj) ? [] : {})

            // 非严格模式下。deepCope k
            //    console.log(arguments.callee===deepCopy)

            // 4.一行
            return Object.entries(obj).reduce((t, [k, v]) => (t[k] = typeof v === "object" ? arguments.callee(v) : v, t), Array.isArray(obj) ? [] : {})
        }

        let student = {
            id: 1,
            grade: { "math": 95, "english": 80 },
            fridens: ["张三", "李四"]
        }

        let p = deepCopy(student)
        p.fridens = []
        p.grade.math=0
        console.log(JSON.stringify(student, null, 2));
        console.log(JSON.stringify(p, null, 2));

    </script>
</body>

</html>

结果

image

标签:isArray,object,return,Object,封装,js,deepCopy,obj,拷贝
From: https://www.cnblogs.com/grblog/p/16790123.html

相关文章