JavaScript对象复制(二)

   <script>
        function copy(a) {
            ret = {};
            for (sth  in a) {
                temp = a[sth];
                if (temp instanceof Array) {
                    var ddddd = [];
                    for (i in temp) {
                        var b = copy(temp[i]);
                        ddddd = ddddd.concat(b);
                    }
                    ret[sth] = ddddd;
                }
                else {
                    ret[sth] = a[sth];
                }
            }
            return ret;
        }
       console.log
       (
               copy({name:"马良",age:"31",Books:[{name:"C#入门经典",title:"好书"},
           {name:"js入门经典",title:"好书"}]}
               )
       );
    </script>

运行上面的代码,发现copy方法不正确,让我的同事李鑫看了一下,后来经过大家的一番讨论,才发现里面的问题。

js语言不严谨,临时变量得使用,在递归调用时容易混淆,解决问题的方式就是不用临时变量,都用直接变量。

改变后得代码如下

   <script>
        function copy(a) {
            ret = {};
            for (sth  in a) {
                if (a[sth] instanceof Array) {
                    ret[sth]=[];
                    for (i in a[sth]) {
                        ret[sth].push(copy(a[sth][i]));
                    }
                }
                else {
                    ret[sth] = a[sth];
                }
            }
            return ret;
        }
        console.log
        (
                copy({name:"马良",age:"31",Books:[{name:"C#入门经典",title:"好书"},
                    {name:"js入门经典",title:"好书"}]}
                )
        );
    </script>

可是改了以后,还是不对,谁能帮助我下。给你发个红包没问题的,100以下的都行。

通过一段时间的技术积累,终于把问题解决了,给大家献上代码

    <script>
        function copy(a) {
            var ret = {};
            for (var sth in a) {
                var temp = a[sth];
                if (temp instanceof Array) {
                    var ddddd = [];
                    for (i in temp) {
                        var b = copy(temp[i]);
                        ddddd = ddddd.concat(b);
                    }
                    ret[sth] = ddddd;
                }
                else {
                    ret[sth] = a[sth];
                }
            }
            return ret;
        }
        console.log
        (
                copy({name:"马良",age:"31",Books:[{name:"C#入门经典",title:"好书"},
                    {name:"js入门经典",title:"好书"}]}
                )
        );
    </script>

结果如下

里面的变量经常会变,经过调查发现之前的变量没有var 关键字,以至于变量都是全局变量,所以上面的代码中的变量前面都加var,保持变量的独立性。

变量 var和不加var的区别在于var 声明的变量是局部变量。不用var生命的变量是全局变量。

原文地址:https://www.cnblogs.com/sexintercourse/p/5679175.html