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 Number
s 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.