pass < or > operator into function as parameter?

拈花ヽ惹草 提交于 2019-12-13 14:30:30

问题


Inside my function there is an if() statement like this:

if(passedValue < staticValue)

But I need to be able to pass a parameter dictating whether the if expression is like above or is:

if(passedValue > staticValue)

But I cant really pass < or > operator in has a parameter, so I was wondering what is the best way to do this?

Also if the language I am using matters its ActionScript 3.0

Thanks!!


回答1:


Instead of passing an operator, which is impossible in AS3, why not pass a custom comparison function?

function actualFunction(passedValue:Number, compareFunction:Function) {
    /* ... */

    if(compareFunction(passedValue, staticValue)) {
        /* ... Do something ... */
    }

    /* ... */
}

Then to use it:

actualFunction(6, function(x:Number, y:Number) {
     return x > y;
});

or:

actualFunction(6, function(x:Number, y:Number) {
     return x < y;
});



回答2:


Why not make the function take a bool as an argument and perform the comparison directly when calling the function?

ExampleFunction(arg1, (passedValue > staticValue))



回答3:


I don't know Actionscript, but can't you make a variable called:

bool greaterThan = true;

and if its true, do >, if its false do < ?




回答4:


You're right, you can't pass operators. You can pass a variable indicating which operator to use though.

lessThan = true;
func(passedValue, lessThan); 


来源:https://stackoverflow.com/questions/2067360/pass-or-operator-into-function-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!