I want to sum values according to arguments received in command-line. Example : when the user types node program.js 5 7 3
, I want the following output :
0: /usr/bin/node
1: /home/<pathtotheprogram>/program.js
2: 5
3: 7
4: 3
5: 15
I am using this loop to pass through the number arguments received in command-line :
process.argv.forEach( (val, index)=> {
//program logic
})
How can I solve this?
Here is a detailed answer.
const args = process.argv;
let sum = 0;
if (args.length > 2) {
for (let i = 2, l = args.length; i < l; i++) {
sum += parseInt(args[i], 10);
}
}
console.log(sum);
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.