从命令行Node.js/js解析多个参数 [英] Parsing multiple arguments from the command line Node.js/js

查看:147
本文介绍了从命令行Node.js/js解析多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,该程序接受任意数量的命令行参数,在这种情况下,使用字符串并将其取反,然后将其输出到控制台.这是我到目前为止的内容:

I'm trying to write a program that takes any number of command line arguments, in this case, strings and reverses them, then outputs them to the console. Here is what I have so far:

let CL = process.argv.slice(2);
let extract = CL[0];

function reverseString(commandInput) {
  var newString = "";
  for (var i = commandInput.length - 1; i >= 0; i--) {
    newString += commandInput[i];
  }
  return console.log(newString);
}

let call = reverseString(extract);

我想不出一种方法来使命令行中的多个参数有效,例如:

I can't figure out a way to make this work for multiple arguments in the command line such as:

node reverseString.js numberOne numberTwo

这将导致如下输出:

enOrebmun owTrebmun 

但是,它对于单个参数(例如:

however it works fine for a single argument such as:

node reverseString.js numberOne

推荐答案

您需要在每个 argv [n ...] 上运行 reverseString()函数>传入的值.正确应用Array.prototype.splice(2)函数后,该函数将删除数组索引0和1(包含命令(/path/to/node )和/path/to/module/file.js ),则需要遍历数组中每个剩余的索引.

You need to run your reverseString() function on each of the argv[n...] values passed in. After correctly applying the Array.prototype.splice(2) function, which removes Array index 0 and 1 (containing the command (/path/to/node) and the /path/to/module/file.js), you need to iterate over each remaining index in the array.

Array.prototype.forEach 方法非常适合此操作,而不需要for循环或map.下面使用的是OP代码,并且是所需输出所需的最少程序(无需过多重构).

The Array.prototype.forEach method is ideal for this, instead of needing a for loop or map. Below is using the OP code and is the minimal program (without much refactor) needed for desired output.

    let CL = process.argv.slice(2);

    function reverseString(commandInput) {
      var newString = "";
      for (var i = commandInput.length - 1; i >= 0; i--) {
        newString += commandInput[i];
      }
      return console.log(newString);
    }

    CL.forEach((extract)=>reverseString(extract))

这是我从终端运行以下代码:

Here is me running this code from the terminal:

这篇关于从命令行Node.js/js解析多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆