Home > other >  Sum for array with While loop JS
Sum for array with While loop JS

Time:02-06

I have tried to make a while loop where I add all the numbers of the array to one sum. I keep on getting an endless loop. I've also tried to do (array.length) (array.length --) (array.length>numbers) But nothing I tried worked... any suggestions? :)

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
    while (array.length>0) {
      sum  = numbers;

      console.log(sum);
    }
  }
}

CodePudding user response:

You don't need the while loop. The for...of loop is going to iterate over the array till its length.

function sumNumbersWhileLoop(array, sum) {
  array = [1, 5, 4, 6, 7];
  sum = 0;
  for (let numbers of array) {
      sum  = numbers;
  }
  console.log(sum)
}

sumNumbersWhileLoop();

If you want to use while, or reduce, then you can do the following:

function sumNumbersWhileLoop() {
  const array = [1, 5, 4, 6, 7];
  let len = array.length - 1;
  let sum = 0;
  while (len >=0) {
    sum  = array[len--];
  }
  console.log(sum);

  // Or use reduce :
  const reduceSum = array.reduce((acc, item) => acc   item, 0);
  console.log(reduceSum);
}

sumNumbersWhileLoop();

CodePudding user response:

You can try this:

function sum(arr, sum) {
    arr = [1, 5, 4, 6, 7];
    sum = 0;
    while (arr.length > 0) {
        sum  = arr.pop();
    }
    return sum;
}
console.log(sum());
  •  Tags:  
  • Related