输入玩家人数,然后使用人数创建玩家数组?

时间:2018-08-07 17:27:15

标签: javascript loops for-loop input while-loop

var n
var players = []

var rl = readline.createInterface(process.stdin, process.stdout);

rl.question("Enter number of players ", function(answer) {
    //Use number of players to generate array of player names

for (n = 0; n < parseInt(answer); n++) {
    var playerNumber = n + 1
    rl.question("Enter name of player " + playerNumber, function(answer) {
        players.push(answer)});
// stops prompting after asking for name of player 1?
    }

});
    rl.close;
rl.on('close', function(){

console.log("The players are: " + players.toString());
});

这直到“输入播放器1的名称”为止,该代码将存储其值。 代码不会提示其他玩家。为什么?

我还尝试用“ while”循环将其替换为“ for”循环,但结果更加糟糕。 它甚至没有开始提示播放器1的名称。为什么会这样呢?感谢您的帮助:)谢谢大家

var readline = require('readline');
var n
var players = []

var rl = readline.createInterface(process.stdin, process.stdout);

rl.question("Enter number of players ", function(answer) {
    //Use number of players to generate array of player names

while (n < parseInt(answer)) {
    var playerNumber = n + 1
    rl.question("Enter name of player " + playerNumber, function(answer) {
        players.push(answer)});
    n++;
// does not even start prompting name of player 1?
    }

});
rl.close;
rl.on('close', function(){

console.log("The players are: " + players.toString());
});

编辑:尝试将rl.close移出循环。问题仍然是一样的,这就是我的控制台中显示的内容:

输入玩家人数

(输入)4

输入玩家1的姓名

(输入)播放器1

(控制台停止提示,当我尝试添加更多名称并结束该过程时,数组仅存储播放器1的名称。)

1 个答案:

答案 0 :(得分:1)

您可以使用递归和回调解决此问题:

const readline = require('readline');

var n
var players = []

var rl = readline.createInterface(process.stdin, process.stdout);

function readPlayers(playerCount, playerArr, curr = 0) {
    if (playerCount == curr) {
        rl.close();
        return;
    }

    rl.question("Enter name of player " + (curr + 1) + ": ", function (playerName) {
        playerArr.push(playerName)
        readPlayers(playerCount, playerArr, curr + 1);
    });
}

rl.question("Enter number of players: ", function (answer) {
    //Use number of players to generate array of player names

    readPlayers(parseInt(answer), players);
});

rl.on('close', function () {
    console.log("The players are: " + players.toString());
});

在满足readPlayers结束递归条件的情况下,这里仅调用一次rl.close。