[英]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.您需要在
reverseString()
每个argv[n...]
值上运行您的reverseString()
函数。在正确应用 Array.prototype.splice(2) 函数后,该函数删除了数组索引 0 和 1(包含命令( /path/to/node
) 和/path/to/module/file.js
),您需要遍历数组中的每个剩余索引。
The Array.prototype.forEach
method is ideal for this, instead of needing a for loop or map. Array.prototype.forEach
方法非常适合这种情况,而不需要 for 循环或映射。 Below is using the OP code and is the minimal program (without much refactor) needed for desired output.下面是使用 OP 代码,是所需输出所需的最小程序(没有太多重构)。
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.