Take a look at the code snippet below:
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
<button id="btn-3">Button 4!</button>
<script type="text/javascript">
var prizes = ['Watch','A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length-1; btnNum++) {
// when any button is clicked...
document.getElementById('btn-' + btnNum).onclick = function() {
// display the corresponding prize from the array
alert(prizes[btnNum]);
};
}
</script>
The intention was to show different array values on clicking different buttons. However, regardless of which button is clicked, only "Fresh Laundry" appears in the alert. There seems to be an issue here where each function assigned in the loop points to the last element in the prizes Array. Why is this happening?