重点案例08-08

  1. List item
<script>
//深拷贝
var obj={
   id:1; 
   name:"张美丽";
   job:{
   a:"前端工程师"
  }
  love:["aa","bb"]
}
var o={};
function deepcopy(newobj,oldobj){
     for(var k in oldobj){
        //获取属性值
       var item=oldobj[k]
       //判断属性值的类型
       if(item instanceof Array){
       newobj[k]=[];
       deepcopy(newobj[k],item);
       }else if(item instanceof Object){
       newobj[k]={};
       deepcopy(newobj[k],item);
       }else{
       newobj[k]=item;
       }
     }
}
 deepcopy(o,obj);
 console.log(obj);
 o.job.a="高级前端"
 o.age=28;
 console.log(o);
</script>
//递归案例
//输入对应的id号,就可以返回想要的数据对象
 var data=[{
    id:1,
    name:'家电',
    goods:[{
        id:11,
        ganme:'冰箱',
        goods:[{
          id:111,
          gname:'海尔',
         },{
           id:112,
           ganme:'美的',
         }]
     },{
       id:12,
       gname:'洗衣机',
     }]
},{
   id:2,
   ganme:'服饰',
}];
function getDataId(json,id){
    var obj={}//定义一个空对象来储存数据
    json.forEach(function(item){
    if(item.id==id){
      obj=item
    }else if(item.goods&&item.goods.length>0){
      obj=getDataId(item.goods,id)
     }
    })
    return obj;
}
console.log(getDataId(data,2));
console.log(getDataId(data,1));
console.log(getDataId(data,11));
console.log(getDataId(data,12));
console.log(getDataId(data,111));
console.log(getDataId(data,112));
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页