打赏

数组深拷贝

<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>数组深拷贝</title>
    </head>
    <body>
        <script type="text/javascript">
            let a1 = [{
                age: 1
            }];
            // 方法一 loadsh
            // 方法二 json
            let a2 = JSON.parse(JSON.stringify(a1))
            a2[0].age = 2
            console.log(a1, a2)
            // 方法3
            let a3 = a1.concat()
            a3[0] = {
                age: 2
            }
            console.log(a1, a3)
            // 方法4
            let a4 = a1.slice()
            a4[0] = {
                age: 3
            }
            console.log(a1, a4)
            // 方法5
            let a5 = a1.splice()
            a5[0] = {
                age: 3
            }
            console.log(a1, a5)
            // 方法6
            function copy(arr) {
                let obj = arr instanceof Array ? [] : {};
                for (let i in arr) {
                    if (typeof arr[i] == 'object' && arr[i] !== undefined) {
                        obj[i] = copy(arr[i])
                    } else if (typeof arr[i] == 'object' && arr[i] == undefined) {
                        obj[i] = null
                    } else {
                        obj[i] = arr[i]
                    }
                }
                return obj
            }
            // 方法7
            let a6 = a1.filter(i => i)
            a6[0] = {
                age: 3
            }
            console.log(a1, a6)
        // 方法8
// Array.from
// 方法9
        // Array.of
</script> </body> </html>

 

posted @ 2019-02-15 14:56  孟繁贵  阅读(4890)  评论(0编辑  收藏  举报
TOP