gpt4 book ai didi

javascript - 如何将变量传递给函数并为其设置新值?

转载 作者:行者123 更新时间:2023-11-29 18:01:35 26 4
gpt4 key购买 nike

我发现很难解释或搜索这个问题,所以我问 Stack Overflow。

我多次要求用户在终端中进行用户输入,并希望从中创建一个功能。接受问题和变量的函数,输入应添加到变量。

这是我的代码:

var name = 'hello',
age = '11'

var readline = require('readline');
// var rl = readline.createInterface(process.stdin, process.stdout);
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var getInput = function(inputVariable, question, cb) {
rl.question(question, function(answer) {
inputVariable = answer;
rl.close();
cb();
});
}

var askForName = function() {
console.log(1,age, name);
getInput(name, "What's your name? ", askForAge);
}
var askForAge = function() {
console.log(2,age, name);
getInput(age, "How old are you? ", printIt);
}
var printIt = function() {
console.log("Hello, " + name);
console.log(".. and " + age + " old.");
}

askForName();

谢谢!

最佳答案

在 node.js 应用程序中,这通常使用回调链或 promise 来解决。

使用回调,您可以编写如下代码:

var getInput = function(question, cb) {
rl.question(question, function(answer) {
// Don't set the variable, but return value to callback
rl.close();
cb(answer);
});
}

// ask* take a callback which they call with the value
var askForName = function(cb) {
getInput("What's your name? ", cb);
}
var askForAge = function(cb) {
getInput("How old are you? ", cb);
}
// printIt takes the values as parameters
var printIt = function(name, age) {
console.log("Hello, " + name);
console.log(".. and " + age + " old.");
}

// Now ask for name and age and store them as local variables
// inside callbacks
askForName(function(name) {
askForAge(function(age) {
printIt(name, age);
});
});

我添加了评论来解释这些变化。基本上,值仅在回调之间传递,从不暴露给另一个范围。

关于javascript - 如何将变量传递给函数并为其设置新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34596564/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com