【问题标题】:I can't understand how JavaScript parses this input. Can someone explain it to me?我不明白 JavaScript 如何解析这个输入。有人可以向我解释吗?
【发布时间】:2017-01-01 20:56:45
【问题描述】:

我正在做一个初学者级别的编程挑战。我了解算法部分,但我不了解它如何获取输入。

我知道它需要三行输入。有一些预先编写的代码将输入放入“输入”变量中。如何处理此“输入”变量以获取单独行中的数据?

输入第 1 行:订购的商品数量,安娜没吃的商品索引

输入第 2 行:每件商品的价格

输入第 3 行:Anna 的成本

示例输入:

4 1

3 10 2 9

12

预期输出:5

这是我正在尝试修复的代码:

function processData(input) {

    var input_temp = input.split("\n");
    var allergyIndex = input_temp[0][1];
    var array = input_temp[1].split(" ");
    var annaCharged = input_temp[2];
    var annaMealsCost = 0;

    for (var i = 0; i < array.length; i++){
        if (i !== allergyIndex){
            annaMealsCost += array[i];
        }
    }

    if (annaMealsCost / 2 === annaCharged){
        console.log("Bon Appetit");
    } else {
        console.log(annaCharged - annaMealsCost / 2);
    } } 

// below is the code that is pre-written, which I don't understand at all:

process.stdin.resume(); process.stdin.setEncoding("ascii");
_input = ""; process.stdin.on("data", function (input) {
    _input += input; });

process.stdin.on("end", function () {    processData(_input); });

【问题讨论】:

  • STDIO 是一种进程间通信的方法。其他一些程序将通过 STDIN(标准输入)发送您的程序数据。当该流向您发送数据时,您需要以某种方式处理它。我建议使用线发射流变换。也许是这样的:github.com/jahewson/node-byline

标签: javascript node.js input


【解决方案1】:

当程序运行时,它将侦听要输入的数据,直到出现EOF 字符。此时,将调用processData,并在此之前输入所有行。

如果您正常运行程序 (node my-program.js),它将等待输入。可以输入数据,最后手动输入Cmd + D触发process.stdinend事件,会被解释为EOF字符。

管道

另一种选择是将输入内容与将其输入文本文件一样。

默认情况下,打印文件将转到process.stdout。但是您可以使用管道字符 (|) 将打印重定向到 process.stdin

input.txt

4 1

3 10 2 9

12

终端提示

cat input.txt | node my-program.js

cat input.txt 命令的输出将用作node my-program.js 的输入。

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2014-10-13
    相关资源
    最近更新 更多