JS HTML:从数组中调用随机函数



我试图调用一个从数组中随机获得的函数。以下是链接:https://codepen.io/Dims09/pen/poRrKWP

现在我有以下代码:JS-

const areoT = document.getElementById("for");
function getValue() {
var randoRandit = [na(), na2(), na3(), na4()];
var rand = randoRandit[Math.floor(Math.random() * randoRandit.length)];
// alert(rand)
// document.getElementById("for").innerHTML=rand;
}

HTML

<div id="for"></div>
<button id="J?2e" onclick="getValue()">CF</button>

我想知道的是如何将它称为"一次性随机项目"。我试过eval()window[](),甚至rand()。有人能帮我吗?

首先,您必须考虑到,每次编写一个标识符并后跟一个带括号的参数列表(即使它是空的(时,您都在调用一个函数。

因此,在这一行:

var randoRandit = [na(), na2(), na3(), na4()];

您调用四个函数,然后将返回的值作为项存储到数组中。这是你真正想要的吗?我想没有。

如果你想引用一个函数而不实际调用它,那么写下它的名称(没有括号(就足够了:

// Declaration:
function myFunction() {...}
// Referenciation:
var f=myFunction;
// Now f acts as a reference to your real function.
// Calling:
f(...)

您只需要在数组中存储函数引用(不包含()(,然后使用rand()调用返回的函数

function na() {
console.log('na() called');
return 'na'
}
function na2() {
console.log('na2() called');
return 'na2'
}
function na3() {
console.log('na3() called');
return 'na3'
}
// array of the function references
var randoRandit = [na, na2, na3];
var rand = randoRandit[Math.floor(Math.random() * randoRandit.length)];
// now call the function
var result = rand();
document.querySelector('div').textContent = result
<div></div>

最新更新