问题
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