Michael Melin Michael Melin - 5 months ago 8
Javascript Question

Make an array filled with numbers 1 to 10000 and then sum all of those numbers

How can I turn this into a function that takes an array of any length and gives you the total?

var points = new Array(100);
for (var i = 0; i < 100; i++) {
points[i] = i + 1;
}

for(var i = 0; i < points.length; i++) {
console.log(points[i]);
}

Answer
function arraysum(arraylength) {
   var arraysum = 0;
   var array1 = new Array();
   for(i=1; i<=arraylength; i++) {
      array1.push(i);
   }
   for(i = 0; i< array1.length; i++) {
      arraysum += array1[i];
   }
   return arraysum;
}

Now when you call the function

arraysum(x)

pass the function some variable or integer for example 1, 15, or 10000.

Comments