简体   繁体   中英

Javascript - Math.random as parameter

I asked this before, but a little vague and poorly worded.

I have a object that takes in Action s and puts them into a stack that it goes through over time. It performs the first Action in the stack until it's done, then it performs the second, and so on. There is a RepeatAction that can take in an array of other Action s and perform them a number of times in a similar fashion. ( .repeat() simply puts a new RepeatAction into the objects stack.

Take this for example:

object.repeat(10,[new LogAction(Math.random())]);

Given that LogAction only takes in a parameter and logs it out. When the object's repeat function gets called it will put 10 LogAction s into its stack, but they will all log the same number. What I'm looking for is a way that it will log a different number all 10 times.

You may say just pass in Math.random as a function, but then what if I want to pass in 4 * Math.random() ?

Any help?

You may say just pass in Math.random as a function,

Yes, I would.

but then what if I want to pass in 4 * Math.random()?

Then in place of Math.random , use

function() { return 4 * Math.random(); }

The code needs to invoke a function (later) to get a different value. eg

// pass in the `random` function - do not get a random number immediately!
object.repeat(10, [new LogAction(Math.random)])

// create and pass in a custom function that uses `random` itself
var rand4 = function () { return Math.random() * 4 }
object.repeat(10, [new LogAction(rand4)])

Since "LogAction" is not disclosed, I'll make a simple example to work with the above.

function LogAction (arg) {
    this.execute = function () {
        // If the supplied argument was a function, evaluate it
        // to get the value to log. Otherwise, log what was supplied.
        var value = (typeof arg === 'function') ? arg() : arg;
        console.log(value);                
    }
}

Reading through How do JavaScript closures work? will likely increase the appreciation of functions as first-class values, which the above relies upon.

You can pass function which returns result of random:

object.repeat(10,[new LogAction(function(){return Math.random();})]);

And in LogAction function you simply need to check if argument is a function:

function LogAction(arg){
    var value = arg&& getType.toString.call(arg) === '[object Function]' ? arg() : arg;

    //log value    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM