简体   繁体   中英

Parsing multiple arguments from the command line 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

which would result in output like this:

enOrebmun owTrebmun 

however it works fine for a single argument such as:

node reverseString.js numberOne

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: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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