简体   繁体   English

轻松执行Node.js程序可打印不确定的结果

[英]Baby steps Node.js program prints indeterministic results

I'm working on the Baby Steps part of "learnyounode", the interactive Node.js tutorial. 我正在研究交互式Node.js教程“ learnyounode”的“婴儿步骤”部分。

Write a program that accepts one or more numbers as command-line arguments and prints the sum of those numbers to the console (stdout). 编写一个程序,该程序接受一个或多个数字作为命令行参数,并将这些数字的总和输出到控制台(stdout)。

Since I know JavaScript from before, I thought it would be rather simple: 由于我以前知道JavaScript,因此我认为这很简单:

var sum = 0;
for (var i = 2; i < process.argv.length; i++) {
  console.log('Adding ' + process.argv[i]);
  sum += Number(process.argv[i]);
}

console.log(sum)

I can't see any problem with this piece of code, but the results seem indeterministic to me! 我看不到这段代码有什么问题,但是结果对我来说似乎不确定!

d:\repos\github\damd\learnyounode>learnyounode run baby_steps.js 1 2 3
Adding 1
Adding 72
Adding 45
Adding 32
150

d:\repos\github\damd\learnyounode>learnyounode run baby_steps.js
Adding 22
Adding 41
Adding 85
Adding 38
186

d:\repos\github\damd\learnyounode>learnyounode run baby_steps.js 10 20 30
Adding 60
Adding 25
Adding 96
Adding 24
Adding 76
Adding 96
Adding 21
Adding 53
Adding 6
Adding 51
Adding 87
Adding 29
Adding 2
Adding 21
Adding 28
Adding 47
Adding 18
Adding 89
829

What's going on here? 这里发生了什么? I'm using Node.js v0.10.34 on Windows 7. 我正在Windows 7上使用Node.js v0.10.34。

The learnyounode in the run functionality supplies arguments of its own (that you are not aware of) without being asked to and ignores your own arguments. 运行功能中的learnyounode提供自己的(您不知道的)自变量,而无需询问并忽略您自己的自变量。

You should run your file calling the good ol' node executable like this: 您应该像下面这样运行文件,以调用良好的ol'节点可执行文件:

node baby_steps.js

Instead of calling the learnyounode executable: 而不是调用learningyounode可执行文件:

learnyounode run baby_steps.js

Note that the verify program expected non deterministic values... Maybe this exercise just intended to use the input as the vector index number (direction) regardless itself value. 请注意,验证程序期望的是不确定的值...也许此练习只是打算将输入用作向量索引号(方向),而不管其本身是什么值。

The reason why those numbers can seems non deterministic could be that argvs[] vector is used to carry non-static values of enviroment (also you're running node on index zero). 这些数字看似不确定的原因可能是argvs []向量用于承载环境的非静态值(同样,您正在索引0上运行节点)。

Remember, learnyounode run function provides you a test enviroment by randomizing the inputs. 请记住, learnyounode运行功能通过随机输入来为您提供测试环境。

Anyway there's a great walkthrough on Github: 无论如何,Github上都有很棒的演练:

https://github.com/leochilds/learnyounode-walkthrough https://github.com/leochilds/learnyounode-walkthrough

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM