Javascript - How to clone an object?

前端 未结 8 1975
悲&欢浪女
悲&欢浪女 2021-02-18 22:28

I am confused. I create a copy from myObjOne, than i delete an entry from myObjOne and JS delete the entry in my copy(myObjTwo) too? But w

8条回答
  •  时光取名叫无心
    2021-02-18 23:00

    Simple.

    var clone=function(o){
          var n= {}.toString.apply(o)=="[object Array]" ? []:{};
          for(i in o)
             n[i]= typeof o[i]=='object' ? clone(o[i]):o[i];
          return n;
     };
    

    Usage:

    var x={a:{d:34},b:33};
    var y=clone(x);  // clones 'x'
    

提交回复
热议问题