I am building an array of functions that will be called at a latter time that looks like:
callbackArray = [];
for(var i = 0; i < 5; i ++) {
callbackArray.push(function() {
console.log(i);
});
}
for(var i = 0; i < callbackArray.length; i ++) {
// This will not preserve the value of i
callbackArray[i]();
}
This will print 4,4,4,4,4. But I need a way to preserve the value of i, so that it doesn't keep the same reference, but creates a new local copy of values. The expected results should be 0,1,2,3,4. This is a simplified example to show the problem. However the variable i, should be anything like objects, arrays, functions, or primitives.
How can I do this?