在HackerRank上使用JavaScript时,有人能帮助我理解Node.js代码的用途吗?

我有一个编码挑战,将使用我不熟悉的HackerRank。 在开始之前,我开始尝试熟悉它,并想象我惊讶,当我在编辑器中看到这个样板代码时!

process.stdin.resume(); process.stdin.setEncoding('ascii'); var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; process.stdin.on('data', function (data) { input_stdin += data; }); process.stdin.on('end', function () { input_stdin_array = input_stdin.split("\n"); main(); }); function readLine() { return input_stdin_array[input_currentline++]; } 

对人力资源部门的其他挑战稍有改动,我不禁要问,究竟发生了什么。 似乎编辑器正在读取某种文本文件,因此可以与我的输出进行比较?

我真的很感激任何有关这方面的见解,因为我非常确定,当我执行我的编码挑战时,我将不得不编写自己的节点“样板”。

谢谢!

代码基本上接收你需要的信息作为挑战的input。 这个特定的一个使得input以与在挑战中描述的相同的方式来进行。

 // Begin reading from stdin so the process does not exit. (basically reading from the command line) process.stdin.resume(); //set the enconding for received data to ascii so it will be readable process.stdin.setEncoding('ascii'); //declare variables to process the data var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; //if data is coming through, put it in the input_stdin string. keep receiving data until no more comes through process.stdin.on('data', function (data) { input_stdin += data; }); //after the transmission when the end signal is received break the string up and push each new line (\n == new line) as an element into the array. process.stdin.on('end', function () { input_stdin_array = input_stdin.split("\n"); main(); }); //gives you one element per line to work with. function readLine() { return input_stdin_array[input_currentline++]; } 

通常这个代码后面跟着一些(在注释行下面)你已经获得variables分配的数据以可用的格式。

还有另一个版本的代码没有作为一口大小的块传递:

 function processData(input) { //Enter your code here } process.stdin.resume(); process.stdin.setEncoding("ascii"); _input = ""; process.stdin.on("data", function (input) { _input += input; }); process.stdin.on("end", function () { processData(_input); }); 

正如你所看到的,代码基本上是一样的,但一些锅炉板“使input可用”是你必须在这一个。

只是不要混淆。 我在那里解决的每一个挑战,我做的第一件事情是console.log(input)或其他预先创build的variables。 它帮助我知道什么是实际的地方。