0

我正在尝试从一组不同的函数中随机选择一个函数。在控制台中它显示“[Function:cycle3]”所以它告诉我正在选择哪个函数,但是函数内部的代码没有运行。如何让随机选择的函数中的代码运行?

    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);
4

2 回答 2

1

我认为给出的原始答案会起作用。如果您也可以使用console.log(randomValue());正如他们所提到的,console.log 会为您提供所需的内容,但是由于您没有调用该函数,因此它不会运行。

于 2021-06-21T00:08:57.173 回答
0

randomValue正在持有不调用它的函数,在行尾添加 () 。

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

然后 randomValue 将保存执行函数的返回值。这没什么。

于 2021-06-20T23:42:42.543 回答