Note that there are some explanatory texts on larger screens.

plurals
  1. POJavascript object reference breaks after changing initial object's value
    text
    copied!<p>I am trying to understand a point of confusion I have with JavaScript objects. Specifically, I am interested in finding what, if anything, causes an object reference to break.</p> <p>To demonstrate the phenomenon, I have included a copy of some output from Chrome's JavaScript console. Note that I am working with arrays here, but we would expect objects to behave similarly given the subtle distinction between arrays and objects in JS. I have added comments for clarity.</p> <pre><code> // Set x to some array literal &gt; x = [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] // Set y to x &gt; y = x [1, 2, 3, 4, 5] &gt; x [1, 2, 3, 4, 5] // as expected &gt; y [1, 2, 3, 4, 5] // as expected </code></pre> <p>As demonstrated above, both <code>x</code> and <code>y</code> output the expected value. Now I shuffle the values of x using a function called <code>shuffle</code> (specified at the bottom of this question).</p> <pre><code> // Shuffle x &gt; x = shuffle(x) [5, 1, 4, 2, 3] &gt; x [5, 1, 4, 2, 3] // x changes as expected &gt; y [5, 1, 4, 2, 3] // y changes as expected </code></pre> <p>Again, everything works as expected above. The variables <code>x</code> and <code>y</code> have maintained reference to the same object. However, when we repeat this operation, the results are strange.</p> <pre><code> // Shuffle x &gt; x = shuffle(x) [3, 1, 5, 4, 2] &gt; x [3, 1, 5, 4, 2] // x changes as expected &gt; y [5, 1, 4, 2, 3] // y didn't change this time </code></pre> <p>Below is the shuffle function, adapted from <a href="https://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array">here</a>. Its purpose is to shuffle the contents of an array (parameter <code>r1</code>) and to return the first <code>n</code> items of the mixed array.</p> <pre><code>function shuffle(r1,n) { var i = r1.length, j, tempi, tempj, r2; r2 = r1; while (--i) { j = Math.floor(Math.random() * (i + 1)); tempi = r2[i]; tempj = r2[j]; r2[i] = tempj; r2[j] = tempi; } return r2.slice(0,n); } </code></pre> <p>I have since fixed the problem by rewriting my shuffle function based on <a href="http://bost.ocks.org/mike/shuffle/" rel="nofollow noreferrer">this function</a>. However, I would still like to understand what's going on. For a quick look at the code in action, I have made a <a href="http://jsfiddle.net/chrisfargen/hc4Jf/" rel="nofollow noreferrer">jsFiddle</a>.</p> <p>Any ideas? I appreciate your time.</p>
 

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