<script type="text/javascript">
function createArray() {
var arr = new Array();
for (var i = 0; i < 10; i++) {
arr[i] = function () {
return i;
}
}
return arr;
}
var funcs = createArray();
for (var i = 0; i < ; i++) {
(funcs[i]() + "<br />");
}
//The above outputs are all the last value of i (10), that is, 10 10 will be output. Obviously this is not what we want
//Reason: Because each function saves the active object of the createArray function, they refer to the same i (value passed by reference)
//Solution: Modify the argument by reference to the argument by value
function createArray() {
var arr = new Array();
for (var i = 0; i < 10; i++) {
arr[i] = function (num) {
return function () {
return num;
}
} (i);//Call this anonymous function and return the internal anonymous function. Here is an extra step to pass parameters by value.
}
return arr;
}
var funcs = createArray();
for (var i = 0; i < ; i++) {
alert(funcs[i]() + "<br />");
}
//The above output is ideal result
</script>