如何使用 JavaScript 中的 readline() 从用户在终端中的输入填充数组? (没有网络)

How to fill an array from user's input in terminal with readline() in JavaScript? (no web)

从用户在终端中提供一些值然后我处理该信息的程序,如:

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question("number 1: ", function(one) {
    rl.question("number 2: ", function(two) {
        rl.question("number 3: ", function(three) {
            if (one > two && one > three) {
                console.log("bigger: " + one);
            } else if (two > one && two > three) {
                console.log("bigger: " + two);
            } else {
                console.log("bigger: " + three);
            }
            rl.close();
        });
    });
});

rl.on("close", function() {
    console.log("\nBYE BYE !!!");
    process.exit(0);
});

我想做类似的事情:使用 readline() 从终端获取用户输入并填充一个数组[10],类似于:

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

var vector = new Array(10);


for (i = 0; i < vector.length; i++) {
    rl.question("value " + (i+1) + ": ", function(one) {
        temp = parseInt(one);
        vector.splice(i, 0, temp);
    });
    if (i = vector.length) {
        rl.close();
    };
};

rl.on("close", function() {
var biggest = Math.max.apply(null, vector);
var smallest = Math.min.apply(null, vector);
console.log("biggest " + biggest + " and smallest " + smallest);
process.exit(0);
});

有什么建议吗?

.question() 很大程度上是异步的。它被赋予一个回调(在未来某个未知的时间执行)并立即 returns 。因此,您的其余代码无需等待即可开展业务。

一种可能的处理方式:

const readline = require("readline");
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const vector = new Array(10);

const handleResults = function(index, vector, answer) {
  // process the answer
  vector[index] = parseInt(answer);

  // start the next question
  index++;
  if(index < vector.length) {
    // ask next question
    rl.question("value " + index + ": ", handleResults.bind(this, index, vector));
  }
  else {
    // we're done, wrap things up
    rl.close();
  }
};

rl.on("close", function() {
  var biggest = Math.max.apply(null, vector);
  var smallest = Math.min.apply(null, vector);
  console.log("biggest " + biggest + " and smallest " + smallest);
  process.exit(0);
});

// Start the questions
rl.question("value 0: ", handleResults.bind(this, 0, vector));

另一个(可能更好的)选择是使用 promises。但是,我会把它留给另一个回答者。