Cycymomo
7/2/2013 - 3:09 PM

deep copy object or array in Javascript

deep copy object or array in Javascript

function deepCopy(obj) {
  if (Object.prototype.toString.call(obj) === '[object Array]') {
    var len = obj.length, out = new Array(len), i = 0;
    for ( ; i < len; i++ ) {
      out[i] = arguments.callee(obj[i]);
    }
    return out;
  }
  if (typeof obj === 'object') {
    var out = {}, i;
    for ( i in obj ) {
      out[i] = arguments.callee(obj[i]);
    }
    return out;
  }
  return obj;
}

/* test case
var a = [[1], [2], [3]];
var b = deepCopy(a);
console.log(a); // [[1], [2], [3]]
console.log(b); // [[1], [2], [3]]
console.log(a === b); // false
b[0][0] = 99;
console.log(a); // [[1], [2], [3]]
console.log(b); // [[99], [2], [3]]*/