Parsing multiple arguments from the command line Node.js/js

回眸只為那壹抹淺笑 提交于 2021-02-10 06:29:06

问题


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

which would result in output like this:

enOrebmun owTrebmun 

however it works fine for a single argument such as:

node reverseString.js numberOne

回答1:


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.

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:



来源:https://stackoverflow.com/questions/54729727/parsing-multiple-arguments-from-the-command-line-node-js-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!