我正在努力使程序重复接受输入并重复它直到输入“退出”。现在循环没有运行,我不知道为什么因为exit变量设置为false。这是我的代码:
var read = require("read");
var exit = false;
function OutsideLoop (exit) {
while(exit === false){
read({prompt: "> "}, function (err, result) {
console.log("");
console.log(result);
console.log("Type in more input or type 'exit' to close the program.");
if(result === "exit"){
exit = true;};
});
};
};
OutsideLoop();
感谢帮助人员。我有一个类似的循环使用if / then而不是while,所以我沿着相同的行重写了这个。
答案 0 :(得分:5)
您已将“exit”声明为函数的参数,因此外部声明对函数内部的逻辑没有影响。调用它时,不会向函数传递任何内容,因此“exit”为undefined
,===
测试失败。
如果您将“退出”传递给该函数,或者从函数声明中取出参数,它将起作用 - 可能。那个“读”函数是异步的,所以我不确定节点的行为方式。
答案 1 :(得分:1)
Pointy对影响您声明的外部变量的参数是正确的。然而,你最终会得到一个可怕的繁忙循环。 Node.js是基于事件的;正确使用它的事件。
function promptUser() {
read({prompt: "> "}, function(err, result) {
console.log();
console.log(result);
console.log("Type in more input or type 'exit' to close the program.");
if(result !== "exit") {
promptUser();
}
});
}
promptUser();
答案 2 :(得分:0)
调用该函数时,您没有通过退出。它应该是:
OutsideLoop( exit );
在最后一行。