JSON浅拷贝和深拷贝

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script>

    var json = {
        "name": "liming",
        "age": "20",
        "height": "160cm",
        "friends": [
            {"name": "xiaoli", "age": "23"},
            {"name": "xiaohah", "age": [
                    {"name": "xiaoli", "age": "23"},
                    {"name": "xiaohah", "age": "23"},
                ]},
        ],
        "2222": [
            {"name": "xiaoli", "age": "23"},
                    {"name": "22222", "age": [
                    {"name": "xiaoli", "age": "23"},
                    {"name": "11111", "age": "23"},
                ]},
        ]
    };

    function copy(json) {
        var newJSon = {};
        for (x in json) {
            if (json[x] instanceof Object) {
               newJSon[x]=copy(json[x])
            } else {
                newJSon[x] = json[x]
            }
        }
        return newJSon;
    }
        //第一种 newJSon =JSON.parse( JSON.stringify(json) )
  第二种:newJSon=copy(json);
    json.name = "xiaoan"
    json.friends[1].name = "xiaoan"
    newJSon.friends[1].age[1].name = "xiaoan12345678op"
    document.write(JSON.stringify(json)+"<br>")
    document.write(JSON.stringify(newJSon))


</script>
</body>
</html>
阅读更多
上一篇json如何复制和复制下一级,且改变其中元素时,原json不会被改变
下一篇抽奖
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭