我有一個包含一些功能的陣列,它看起來像這樣:運行函數隨機
var all_questions = [
show_question(1, 1),
show_question(2, 1),
show_question(3, 1),
];
我想運行這些功能集成到該數組隨機。我怎樣才能做到這一點?
我有一個包含一些功能的陣列,它看起來像這樣:運行函數隨機
var all_questions = [
show_question(1, 1),
show_question(2, 1),
show_question(3, 1),
];
我想運行這些功能集成到該數組隨機。我怎樣才能做到這一點?
首先,您需要將這些函數包裝在匿名函數中,否則將立即調用它們。從那裏,你可以get a random element from the array並調用它,就像這樣:
var all_questions = [
function() { show_question(1, 1) },
function() { show_question(2, 1) },
function() { show_question(3, 1) },
];
all_questions[Math.floor(Math.random() * all_questions.length)]();
function show_question(a, b) {
console.log(a, b);
}
需要注意的是,你可以通過只在一個隨機化函數的第一個參數而已,而不是存儲函數引用提高邏輯陣列:
function show_question(a, b) {
console.log(a, b);
}
var rnd = Math.floor(Math.random() * 3) + 1;
show_question(rnd, 1);
像
var all_questions = [
function() show_question(1, 1),
function() show_question(2, 1),
function() show_question(3, 1),
];
var x = Math.floor((Math.random() * 3) + 1);
// do something you want
all_questions[x];
如果您呼叫使用不同的參數相同的功能,我會說這是一個更好的選擇,選擇的參數,而不是隨機的功能。
var args = [
[1,2],
[1,3],
[1,4],
...
]
// Get a random element from the array
// http://stackoverflow.com/a/4550514/558021
var randomArgs = args[ Math.floor(Math.random()*args.length) ];
show_question.apply(this, randomArgs);
這裏使用apply function是因爲它將參數傳遞給目標函數的方式。當你使用apply
來執行一個函數時,你想傳遞給該函數的參數在一個數組中被提供,然後在被傳遞給目標函數時被分離成單獨的參數。
你可以使用'show_question.apply(randomArgs)'和OP不需要修改函數在所有。 –
我認爲,但最終選擇了這種方法,因爲我覺得它會更好地適應這個問題的能力水平。 – Lix
我可以理解,雖然國際海事組織最好把某人提升到你的水平,而不是迎合他們的水平。 –
你可以這樣做;
var allQuestions = [
showQuestion.bind(this, 1, 1),
showQuestion.bind(this, 2, 1),
showQuestion.bind(this, 3, 1),
],
displayQuestion = allQuestions[~~(Math.random()*allQuestions.length)];
所有功能都會在數組創建時執行 –
爲什麼要這樣做? – Liam
要擴展@ RajaprabhuAravindasamy的評論 - 函數名稱末尾的括號是實際「調用」函數的內容。 – Lix