Passing modified array as an argument to function
<p>I've been struggling with the below piece of code for far too long, trying to figure out how to pass the array which is being modified with every click to the function.</p>

<p>The problem is that as soon as the clickedLinks array is modified it affects the passedLinks array in the shoplist function.</p>

<p>I even got <a href="http://stackoverflow.com/a/12061738/932210">a great explanation</a> of why this is happening but I'm not able to apply it correctly to my example. I tried clearing the array at different points but that didn't work out. I'm starting to doubt if the whole logic of my code is flawed.</p>

<p>Any help would be appreciated.</p>

<p>Here is the code:</p>

<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;
      Test 1
    &lt;/title&gt;
    &lt;script src="http://code.jquery.com/jquery-latest.js" type=
    "text/javascript"&gt;
&lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div class="items"&gt;
      &lt;ul&gt;
        &lt;li&gt;
          &lt;a href="#" id="link1"&gt;Link 1&lt;/a&gt;
        &lt;/li&gt;
        &lt;li&gt;
          &lt;a href="#" id="link2"&gt;Link 2&lt;/a&gt;
        &lt;/li&gt;
        &lt;li&gt;
          &lt;a href="#" id="link3"&gt;Link 3&lt;/a&gt;
        &lt;/li&gt;
        &lt;li&gt;
          &lt;a href="#" id="link4"&gt;Link 4&lt;/a&gt;
        &lt;/li&gt;
      &lt;/ul&gt;
    &lt;/div&gt;

&lt;script type="text/javascript"&gt;
    var clickedLinks = [];
    var passedItems = [];


    // Collect clicked link IDs into an array and pass the array as an argument to shoplist()
    $('.items a').click(function () {

    if (clickedLinks.indexOf(this.id) != -1) {
        var linkIndex = clickedLinks.indexOf(this.id);
        clickedLinks.splice(linkIndex, 1);
    } else {
        clickedLinks.push(this.id);
    }

    shoplist(clickedLinks);

    });


    function shoplist(ids) {
        passedItems.push(ids);
        alert(passedItems);
    }
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p><strong>Steps:</strong></p>

<ol>
<li>Click "Link 1"</li>
<li>Click "Link 2"</li>
</ol>

<p><strong>Expected Result:</strong> Alert window displays "link1, link1, link2"</p>

<p><strong>Actual Result:</strong> Alert window displays "link1, link2, link1, link2"</p>
