2011/10/21 Rahul <[email protected]>:
> function buildList(list){
> var arrFun = new Array();
> for(var x = 0; x < list.length; x++){
> arrFun[x] = function()
> { alert(" NUMBER "+list[x]); }
> }
> return arrFun;
> }
>
> function fn27(){
> var arr = buildList([23,45,67]);
> for(var x = 0; x < arr.length; x++){
> arr[x]();
> }
> }
>
> window.onload = fn27();
>
> here, on page onload there is a three times alert as "NUMBER
> undefined",
> why so ?
> why list[x] is not holding the value which was assigned initially.
>
> waiting for the reply
The value x is out of bonds by the time you call the functions. So x
is a closure variable, and the value of it is list.length+1 by the
time the function finished executing. This gives you an undefined
value, as there is no defined value for that index in the array. There
are several ways to fix that.
function buildList(list) {
var arrFun = [];
function callback(y) {
// y is a closure variable
return function() {
alert(" NUMBER " + list[y]);
};
}
for (var x = 0; x < list.length; x++) {
arrFun[x] = callback(x);
}
return arrFun;
}
--
Poetro
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]