0

Hi I want to create several function which work similar but use a slightly different value. I cannot change the parameters because I use these for a callback of a library. My first idea:

for(i = 0; i < 3; i++) {
  f = function() {
    console.log(i);
  };
}

This obviously copies a refence of i to the function but I rather want to value at that time so that each function outputs a different value. I appreciate your help.

1 Answer 1

2

you may try this way:

var f=[];    
for(i = 0; i < 3; i++) {
      f[i] = (function(index) {   
            return function() {          
                console.log("My value: " + index);
            } 
        })(i);
    }

working demo here

Sign up to request clarification or add additional context in comments.

1 Comment

Have you check demo this will create 3 functions having different values (this idea come from "but use a slightly different value").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.