I cant figure out how to create a unique copy of an associate array. I
need to create a backup of an array, but since arrays and objects are
always passed by reference in javascript it ends up replicating
whatever changes I do to the first array over to the backup. I would
use the .slice() method but since the arrays are not initialized with
new Array() it doesn't have that functionality. I've managed to get it
to work using the following code, but when combined with jQuery it
crashes the browser:

      Object.prototype.clone = function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
          if (i == 'clone') continue;
          if (this[i] && typeof this[i] == "object") {
            newObj[i] = this[i].clone();
          } else newObj[i] = this[i]
        } return newObj;
      };

      test = {'foo':{'bar':'orig message'}};
      test2 = test.clone();
      test3 = test;

      test2['foo']['bar'] = 'new message';
      alert(test2['foo']['bar']);
      alert(test3['foo']['bar']);

Any suggestions?

Reply via email to