0

I want to run a file that adds up the values in the command line. So, node myscript 1 5 10 returns 16.

However, it seems that in my code, sum changes into an array variable - somehow. I'd like to know why this happens, and what the correct formulation should be.

var array = process.argv;
var count = array.length - 1;
var i = 2;
var sum = 0;

console.log("There are " + (count - 1) + " individual numbers.");

while (i <= count) {
    sum += array[i];    
    i++;
}

console.log(sum);
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Dan
  • 516
  • 5
  • 14
  • Could be wrong but the math seems off on your _"There are " + (count - 1) + " individual numbers."_ statement. `array.length` will give you the number of individual numbers. `array.length - 1` (or count) will give you the last value's `index` in the array. `array.length - 2` (which is the same as `count - 1` will give you the next to last value's index in the array, not the total number of individual numbers. – War10ck May 30 '14 at 16:04
  • [Because that's how Node.js works.](http://nodejs.org/docs/latest/api/process.html#process_process_argv) – Ram May 30 '14 at 16:07
  • @undefined: OP is aware `array` is an array, but is confused about what `sum` is. – gen_Eric May 30 '14 at 16:07

2 Answers2

4

The input variables are given as Strings and not Numbers, so in order to sum them up, you need to convert them to numbers:

sum += +array[i];

// or

sum += parseInt( array[i], 10 );

In your current code, you concatenate the Strings (and sum's initial value gets converted to a String as well).

Sirko
  • 72,589
  • 19
  • 149
  • 183
0

The problem is that array is an array of strings, not numbers. This means that 0 is being turned into a string "0" and then concatenated with other string variables.

You could turn array into an array of Numbers like this:

array = argv.slice(1).map(Number)

Note that I have removed the first entry, the name of the program, using slice.

You can now loop through array starting from element 0 and your code will work as expected.

Working example (making use of the esoteric --> operator ;)

var array = argv.slice(1).map(Number);
var count = array.length;
var sum = 0;

console.log("There are " + count + " individual numbers.");

while (count --> 0) sum += array[count];
console.log(sum);

update

Instead of using map, you may as well use reduce:

var array = argv.slice(1);
console.log("There are " + array.length + " individual numbers.");
var sum = array.reduce(function(prev, curr) { return prev + +curr }, 0);
console.log(sum);

reduce combines all of the values of array using the function provided. The unary + operator is used to convert the values in array to numbers. The second argument is the initial value of the sum.

Community
  • 1
  • 1
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141