【问题标题】:In JavaScript, I'm randomly selecting a function, however when that function is selected, the code inside it is not run在JavaScript中,我随机选择一个函数,但是在选择该函数时,它内部的代码不会运行
【发布时间】:2021-06-20 23:39:40
【问题描述】:

我正在尝试从一组不同的函数中随机选择一个函数。在控制台中它显示“[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);

【问题讨论】:

  • 要运行它,您仍然需要调用它:randomValue()。与记录cycle1cycle1() 的区别相同。

标签: javascript node.js robotjs


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 由于这些函数都没有返回任何内容,我认为不应在此处添加调用 - randomValue 变量将毫无用处。
    • 我以为 console.log 只是一次性调试
    • 这仍然是一个有效的解决方案。
    • 我想把这个命令(随机选择一个函数的命令)放在一个变量中,然后在程序的其他地方使用这个变量?因为我尝试将结果存储在 x 中," var x = randomValue():" 但是我不允许在函数外部使用该变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-27
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多