zoukankan      html  css  js  c++  java
  • nodeschool.io 2

     ~~  BABY STEPS  ~~

    Write a program that accepts one or more numbers as command-line

    arguments and prints the sum of those numbers to the console (stdout).

    ----------------------------------------------------------------------
    HINTS:

    You can access command-line arguments via the global `process` object.
    The `process` object has an `argv` property which is an array
    containing the complete command-line. i.e. `process.argv`.

    To get started, write a program that simply contains:

    console.log(process.argv)

    Run it with `node myprogram.js` and some numbers as arguments. e.g:

    $ node myprogram.js 1 2 3

    In which case the output would be an array looking something like:

    [ 'node', '/path/to/your/program.js', '1', '2', '3' ]

    You'll need to think about how to loop through the number arguments so
    you can output just their sum. The first element of the process.argv
    array is always 'node', and the second element is always the path to
    your program.js file, so you need to start at the 3rd element
    (index 2), adding each item to the total until you reach the end of
    the array.

    Also be aware that all elements of `process.argv` are strings and you
    may need to coerce them into numbers. You can do this by prefixing the
    property with `+` or passing it to `Number()`. e.g. `+process.argv[2]`
    or `Number(process.argv[2])`.

    learnyounode will be supplying arguments to your program when you run
    `learnyounode verify program.js` so you don't need to supply them
    yourself. To test your program without verifying it, you can invoke it
    with `learnyounode run program.js`. When you use `run`, you are
    invoking the test environment that learnyounode sets up for each
    exercise.

    var total = 0;
    
    process.argv.forEach(function(val, index, array) {
      if(index>1){
              total += Number(val);
      }
    
    });
    
    console.log(total);

    官方例子:

    var result = 0
    
    for (var i = 2; i < process.argv.length; i++)
      result += Number(process.argv[i])
    
    console.log(result)

    《node.js开发指南》P59

    process 是一个全局变量,即 global 对象的属性。它用于描述当前 Node.js 进程状态
    的对象,提供了一个与操作系统的简单接口。通常在你写本地命令行程序的时候,少不了要
    和它打交道。下面将会介绍 process 对象的一些最常用的成员方法。
     process.argv是命令行参数数组,第一个元素是 node,第二个元素是脚本文件名,
    从第三个元素开始每个元素是一个运行参数。

  • 相关阅读:
    DockerPush
    DockerInstall
    DockerFile
    基于虚拟机实例/java程序线程的虚拟机内存分配
    Class文件结构及方法中的指令
    JAVA类型生命周期的开始阶段和使用阶段/以及创建对象的几种方式
    。。。。。毕业季
    PCA算法
    ffmpeg将图片转为视频
    Linux下使用bgslibrary的OpenCv库
  • 原文地址:https://www.cnblogs.com/della/p/3457924.html
Copyright © 2011-2022 走看看