Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I plan on releasing this code in the next version of <a href="http://jpaq.org/" rel="nofollow">jPaq</a>, but until then, you can use this if your goal is to do a deep copy of arrays:</p> <pre><code>Array.prototype.clone = function(doDeepCopy) { if(doDeepCopy) { var encountered = [{ a : this, b : [] }]; var item, levels = [{a:this, b:encountered[0].b, i:0}], level = 0, i = 0, len = this.length; while(i &lt; len) { item = levels[level].a[i]; if(Object.prototype.toString.call(item) === "[object Array]") { for(var j = encountered.length - 1; j &gt;= 0; j--) { if(encountered[j].a === item) { levels[level].b.push(encountered[j].b); break; } } if(j &lt; 0) { encountered.push(j = { a : item, b : [] }); levels[level].b.push(j.b); levels[level].i = i + 1; levels[++level] = {a:item, b:j.b, i:0}; i = -1; len = item.length; } } else { levels[level].b.push(item); } if(++i == len &amp;&amp; level &gt; 0) { levels.pop(); i = levels[--level].i; len = levels[level].a.length; } } return encountered[0].b; } else { return this.slice(0); } }; </code></pre> <p>The following is an example of how to call this function to do a deep copy of a recursive array:</p> <pre><code>// Create a recursive array to prove that the cloning function can handle it. var arrOriginal = [1,2,3]; arrOriginal.push(arrOriginal); // Make a shallow copy of the recursive array. var arrShallowCopy = arrOriginal.clone(); // Prove that the shallow copy isn't the same as a deep copy by showing that // arrShallowCopy contains arrOriginal. alert("It is " + (arrShallowCopy[3] === arrOriginal) + " that arrShallowCopy contains arrOriginal."); // Make a deep copy of the recursive array. var arrDeepCopy = arrOriginal.clone(true); // Prove that the deep copy really works by showing that the original array is // not the fourth item in arrDeepCopy but that this new array is. alert("It is " + (arrDeepCopy[3] !== arrOriginal &amp;&amp; arrDeepCopy === arrDeepCopy[3]) + " that arrDeepCopy contains itself and not arrOriginal."); </code></pre> <p>You can play around with this code <a href="http://jsbin.com/jPaq-Array.clone/2" rel="nofollow">here at JS Bin</a>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload