Array reference issues when using within a function created inside a loop
<p>I know, great title right ;-)</p>

<p>Anyway, lets say I have the following code (which I do):</p>

<pre><code>function GetArray(i) {
    if (i == 0) {
        return [1, 2, 3];
    }
    return [];
}

for (var i = 0; i &lt; 3; i++) {
    var array = GetArray(i);

    var onClick = function() {
        alert(array.length);
    }

    var html = "&lt;a&gt;click me&lt;/a&gt;&lt;br/&gt;";
    var element = $(html);
    $("div").append(element);

    element.click(onClick);
}​
</code></pre>

<p><a href="http://jsfiddle.net/XFBNA/" rel="nofollow">See working code here</a></p>

<p>Click the 3 links, and notice the alert with the value of 0 for each.</p>

<p>What I want is for the first link to alert 3 when clicked.</p>

<p>Now, before you all start shouting why this is happening, I get that the onClick function is clearing using a reference to the same instance of the array, and thus each iteration of the loop "changes" the array, rather than creating a new one, this is why in effect the last array value is used for all click events.</p>

<p>So the question is, what can I do to get the job done?</p>

<p>I thought of trying to "clone" the array inside the function the that didn't work (I used <code>.slice(0)</code>) and probably rightly doesn't work. Plus, I am guessing the it may even just be that the exact same function is being used for all 3 events.</p>
