【问题标题】:I want to store user entered vaule in some variable and use in another function or want to some opeartion on user input data我想将用户输入的值存储在某个变量中并在另一个函数中使用,或者想对用户输入数据进行一些操作
【发布时间】:2021-08-09 09:55:28
【问题描述】:
const readline = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout,
})

readline.question('Enter number 1', function (a) {
  readline.question('Enter number 2', function (b) {
    //`i want to store user entered vaule in some variable and use in another function like sum`
    var one = a
    var two = b
    readline.close()
  })
})


function sum(one,two) {
  return one + two
}

我的动机是存储用户输入的值并对其执行一些操作或存储以使用输入值调用另一个函数。我怎样才能做到这一点?

在像 C++ 这样的另一种语言中它非常简单,但在 node.js 中我无法弄清楚。

请注意,我不想使用提示,我希望用户从控制台提供输入

【问题讨论】:

    标签: javascript node.js variables console user-input


    【解决方案1】:

    在另一个函数中使用作用域变量的最简单方法之一是将它们作为函数的参数传入。例如

    const readline = require('readline').createInterface({
      input: process.stdin,
      output: process.stdout,
    })
    
    readline.question('Enter number 1', function (a) {
      readline.question('Enter number 2', function (b) {
        //`i want to store user entered vaule in some variable and use in another function like sum`
        const result = sum(a, b);
        console.log(`The result of running my function is ${result}`);
        readline.close()
      })
    })
    
    
    function sum(first,second) {
      return first + second;
    }
    

    【讨论】:

    • 如果我没有功能我只想存储输入值,还有其他方法吗
    • @Infinity 这是一个很难回答的问题,因为它非常模糊。但总的来说,由于 node.js 的异步特性,当涉及到依赖于 IO 等异步行为的全局变量的想法时,您会受到很大的限制。问题是,即使您在回调函数范围之外定义了一个变量,然后在回调函数内部为其分配了值,也不能保证回调函数将在您在外部使用变量时运行回调范围。我认为阅读 node.js async 的工作原理是一个好的开始。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多