0

I have a function that looks through arrays and returns ether true or false and will change a global variable to the number that it found if it was above 0. I want to have a if statement that changes so if it is that number it'll call a different function based on that number without having multiple if statements. So something like

if(left == true){
    for(i=1;i<8;i++){
        if(leftnumber == i){
            //function based on i
        }
    }
}
3
  • Why can't you just pass the function an argument? Commented May 20, 2015 at 16:52
  • Why don't you just make the function dynamic instead of the condition? Btw, what is the function and what does it do? Commented May 20, 2015 at 16:52
  • I think you search for the switch statement. Commented May 20, 2015 at 16:53

2 Answers 2

1

You can use an object to lookup a function based on the number.

// object that stores functions based on "leftnumber"
var fnTable = { };

// when "leftnumber" is 6, this function will be called
fnTable[ 6 ] = function() { ... };

// ... for loop stuff

// attempt to find the function for the value at i
var lookup = fnTable[ i ];

// if it exists, call it
if (lookup)
    lookup( );
Sign up to request clarification or add additional context in comments.

Comments

0

Something like this?

function myfunction(number){
    //do stuff
}

if(left == true){
    for(i=1;i<8;i++){
        if(leftnumber == i){
            myfunction(i);
        }
    }
}

1 Comment

Or simple: if(left){ myfunction(leftnumber); }

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.