Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第54题(2019-10-10):实现一个函数clone,可以对JavaScript中的5种主要的数据类型(包括Number、String、Object、Array、Boolean)进行值复制 #56

Open
qappleh opened this issue Oct 10, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Oct 10, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Oct 11, 2019

考察点1:对于基本数据类型和引用数据类型在内存中存放的是值还是指针这一区别是否清楚
考察点2:是否知道如何判断一个变量是什么类型的
考察点3:递归算法的设计

// 方法一:
Object.prototype.clone = function(){ 
   var o = this.constructor === Array ? [] : {};
     for(var e in this){
       o[e] = typeof this[e] === "object" ? this[e].clone() : this[e];
     }
   return o;
}  

//方法二:
/** 
 * 克隆一个对象
 * @param Obj      
 * @returns    
 */ 
function clone(Obj) {
  var buf;
  if (Obj instanceof Array) {
    buf = [];                    
    //创建一个空的数组
    var i = Obj.length;
    
    while (i--) {
      buf[i] = clone(Obj[i]);
    }
    return buf;
  }  else if (Obj instanceof Object){
    buf = {};                   
    //创建一个空对象
    for (var k in Obj) {           
      //为这个对象添加新的属性
      buf[k] = clone(Obj[k]);
    }
    return buf;
  } else {                         
    //普通变量直接赋值32             
    return Obj;
  }
}  

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant