1

I have a function that has a couple of for statements in it. I need to be able to pass code to the for statements via parameters.

var a = function(paramCode){
    for(var eachRow=0; eachRow<20; eachRow++){
        for(var eachCol=0; eachCol<20; eachCol++){
            paramCode
        }
    }
}

a({ //the code I want to pass is surrounded in the function pointers
    if(array[x][y]){
        //do something
    }
});

This is a basic version of what I'm trying to do. The only problem is the error I get in the console.

Uncaught SyntaxError: Unexpected token [

I would love to know how to fix this error, or a way that I can still do what I'm trying to do.

1 Answer 1

4

You could create a callback, this is a function which is handed over to the calling function as parameter.

var a = function (callback) {
        for (var eachRow = 0; eachRow < 20; eachRow++) {
            for (var eachCol = 0; eachCol < 20; eachCol++) {
                callback(array, eachRow, eachCol);
            }
        }
    };

a(function (array, x, y) {
    if (array[x][y]){
        //do something
    }
});
Sign up to request clarification or add additional context in comments.

Comments

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.