[英]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.