I have a blank array and i need to add the numbers from 1 to 20 to this array. After that i need to sum these number totally. I am stucked in here:
for(i=1;i<=20;i++){
    push()
}
What do you think, please answer. Thank you
I have a blank array and i need to add the numbers from 1 to 20 to this array. After that i need to sum these number totally. I am stucked in here:
for(i=1;i<=20;i++){
    push()
}
What do you think, please answer. Thank you
 
    
    Let's see... First you need to define an array like so:
var array =[];
And you also need to make a variable for the sum:
var sum = 0;
Now you use that for loop to add your numbers to the array:
for(var i = 0; i <= 20; i++)
{
    array[i] = i;
    sum += i;
}
Hopefully this is what you were looking for.
 
    
    If I got your question correctly, this should help :
var i = 1,
    sum = 0,
    numbers = [];
// Filling the array :
for(i=1; i<=20; i++){
    numbers.push(i);
}
// Calculating the sum :
numbers.forEach(function(number) {
    sum += number;
});
And to see the result :
alert(sum);
 
    
    yeah you can achieve it simply just by making a push() function to the array variable like:
<script>
  function helloWorld(){
   var arr = Array();
   var sum = 0;
   for(var i=0;i<20;i++){
     arr.push(i+1);
     sum = sum+(i+1);    
   }
   console.log(arr,sum);
  }
</script>
in the console.log you will get the result
 
    
    another way to do it is with the use of reduce
  var arr = [];
      for(i=1;i<=20;i++){  //a for loop to create the array
        arr.push(i)
    }
    console.log("the value of the array is " + arr)
    var sum = arr.reduce(add, 0);
    function add(a, b) { // a function the calculate the total
        return a + b;
    }
    console.log("the total is " + sum)
 
    
    This is an alternative using the function Array.from to initialize and the function reduce to sum the whole set of numbers.
var numbers = Array.from({length: 20 }, () => ( this.i = ((this.i || 0) + 1 )) ); //0,1,2,3.... and so on!
    sum = numbers.reduce((a, n) => a + n, 0);
    
console.log(sum);