问题描述
我试图从不同函数的数组中随机选择一个函数。在控制台中,它说“[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);
解决方法
我认为给出的原始答案会起作用。如果您console.log(randomValue());
,它也可以工作,正如他们所提到的,console.log 为您提供了您想要的东西,但由于您没有调用该函数,因此它不会运行。
randomValue
持有不调用它的函数,在行尾添加 ()。
var randomValue = myArray[Math.floor(Math.random() * myArray.length)]();
然后 randomValue 将保存执行函数的返回值。这没什么。