As a javascript beginner, I thought I realized the Closure feature until seeing the trap from the sample code below. I tried to modify the code to pop up the result which many C/C++/C#/Java programmers expect as,
"item1 1"
"item2 2"
"item3 3"
After one hour struggling, I still can't do that. Could any javascript master teach me how to modify it ? Thank you.
function buildList(list) {
var result = [];
for (var i = 0; i < list.length; i++) {
var item = 'item' + list[i];
result.push( function() {alert(item + ' ' + list[i])} );
}
return result;
}
function testList() {
var fnlist = buildList([1,2,3]);
// Using j only to help prevent confusion -- could use i.
for (var j = 0; j < fnlist.length; j++) {
fnlist[j]();
}
}
testList();