Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // So the problem was that we are declaring function inside
- // for loop, which has variable i that is global for inner function because it is declared as var.
- // So everytime we create a function, the variable i is changed,
- // and eveytime the i changes, the funciton is keeping last value.
- // As a solution we can declare i as let, so that it will be local variable and everytime,
- // i changes old value will be kept
- function createArrayOfFunctions(y) {
- var arr = [];
- for (let i = 0; i < y; i++) {
- arr[i] = function (x) {
- return x + i;
- }
- }
- return arr;
- }
- let a = createArrayOfFunctions(3)
- console.log(a[0](1))
- console.log(a[1](1))
- console.log(a[2](1))
Add Comment
Please, Sign In to add comment