I have a function inside a loop that changes it's returned value in each iteration and I want to save all the returning value of the function in an array.
What's wrong with this code:
function riddle() {
var a = [];
for (var i = 0; i < 10; i++) {
a.push(function() {
return i * i;
});
}
return a;}
// code to test your solution:
var a = riddle();
var b = [];
for (var i = 0; i < a.length; i++) { b.push(a[i]()); }
console.log(b);
This what supposed to be printed:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
But instead I get this:
[100, 100, 100, 100, 100, 100, 100, 100, 100, 100]