0

I am trying to randomly select a function from an array of different functions. In the console it says "[Function: cycle3]" so it IS telling me which function is being chosen, however the code inside the function is not ran. How can I get the code inside the randomly chosen function to run?

    var robot = require('robotjs');

    function cycle1() {
        robot.moveMouse(0,0)
    }

    function cycle2() {
        robot.moveMouse(1920, 1080);
    }

    function cycle3() {
        robot.moveMouse(0, 1080);
    }

    var myArray = [cycle1, cycle2, cycle3];

    var randomValue = myArray[Math.floor(Math.random() * myArray.length)];
    console.log(randomValue);
  • 1
    To run it, you still need to call it: `randomValue()`. Same as the difference between logging `cycle1` and `cycle1()`. – Bergi Jun 20 '21 at 23:42

2 Answers2

1

I think the original answer given would work. It would also work if you console.log(randomValue()); As they mentioned, the console.log is giving you what you want, but since you're not invoking the function, it isn't going to run.

funtkungus
  • 238
  • 1
  • 2
  • 12
0

randomValue is holding the function not invoking it, add () at the end of the line.

var randomValue = myArray[Math.floor(Math.random() * myArray.length)]();

then randomValue will hold the returned value of the executed function. which is nothing.

Raphael PICCOLO
  • 2,095
  • 1
  • 12
  • 18
Ravenscar
  • 2,730
  • 19
  • 18
  • 1
    Since none of these functions return anything, I don't think that's where the call should be added - the `randomValue` variable would be useless. – Bergi Jun 20 '21 at 23:43
  • 1
    I had assumed the console.log was just a throwaway debug – Ravenscar Jun 20 '21 at 23:47
  • it's still a valid solution. – Raphael PICCOLO Jun 20 '21 at 23:58
  • I want to put this command (the command that randomly picks a function) and store the result in a variable and use that variable else where in the program? Because I tried storing the result in x, " var x = randomValue():" however I am not allowed to use that variable outside the function. –  Jun 21 '21 at 02:33