Home > database >  show random number from string
show random number from string

Time:10-21

i have 5 different numbers. What is the options, to choose random number from string and return it? callback meaning callback function

function amazing(callback) {
    const num = callback(42, 128, 37, 81, 66);
    document.write("Num: "   num);
}

CodePudding user response:

actually i found a solution, but may be it is another option?

function amazing(callback) {
    const num = callback(42, 128, 37, 81, 66);
    document.write("Num: "   num);
}


function test () {
    amazing((a,b,c,d,e) => {
        const arr = [a,b,c,d,e]
        index  = Math.floor(Math.random() * arr.length);
        return arr[index]
    })
}

CodePudding user response:

If you're looking for a function that picks one of its arguments at random, it goes like this:

let randomArg = (...args) => 
    args[Math.floor(Math.random() * args.length)];


console.log(randomArg(1,2,3,4))

However, in most cases, you'd want this function to accept an array rather than a list of arguments:

let randomItem = (arr) => 
    arr[Math.floor(Math.random() * arr.length)];


console.log(randomItem([1,2,3,4])) // note the [...]

You can pass this function as a parameter like any other function:

let randomItem = (arr) => 
    arr[Math.floor(Math.random() * arr.length)];
    
function makeAChoice(chooser) {
  let choosenItem = chooser([1,2,3,4])
  console.log("choice:", choosenItem)
}

makeAChoice(randomItem)

Hope this helps.

  • Related