[英]How to make a function in Node JS run only once
我正在用 JS 創建一個簡單的 tictactoe 終端游戲。 我使用名為 player1Input 的變量來獲取用戶提示。 如果提示不等於“X”,我再次調用該函數以確保用戶輸入正確的輸入。 如果我多次輸入錯誤的輸入,函數 (player1Game) 最終會被調用多次而不是一次。 我如何讓它只被調用一次。 我在底部放了一段代碼。我注釋了使函數運行兩次的代碼部分
function player1Game () {
let player1Input = prompt(`${player1Name.charAt(0).toUpperCase() + player1Name.slice(1) } please enter \"x\": `);
//Create an error that responds if player 1 does not type x
if (player1Input !== "x") {
console.log("Please make sure you type in x")
player1Game();
//the function runs multiple times here instead of once.
// How do I get it to run only once.
}
您仍然沒有在此處顯示整個上下文,但也許您只需要在再次調用它后return
,以便在函數不滿足輸入要求時函數的其余部分不會執行:
function player1Game () {
let player1Input = prompt(`${player1Name.charAt(0).toUpperCase() + player1Name.slice(1) } please enter \"x\": `);
//Create an error that responds if player 1 does not type x
if (player1Input !== "x") {
console.log("Please make sure you type in x")
player1Game();
// return so it doesn't execute any more of the function
return;
}
// code here will only get called if the `player1Input`
// meets the above critera
// Rest of your code here...
}
或者,您可以使用if/else
:
function player1Game () {
let player1Input = prompt(`${player1Name.charAt(0).toUpperCase() + player1Name.slice(1) } please enter \"x\": `);
//Create an error that responds if player 1 does not type x
if (player1Input !== "x") {
console.log("Please make sure you type in x")
player1Game();
} else {
// code here will only get called if the `player1Input`
// meets the above critera
// Rest of your code here...
}
}
僅供參考,這里沒有什么特別的。 這只是 Javascript 中的正常功能控制流。 如果您不想執行更多函數,請插入return
語句。 或者使用if/else
保護代碼分支,以便條件控制執行哪些代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.