Home > Enterprise >  Sum function using slice only takes first few items
Sum function using slice only takes first few items

Time:12-31

I want to get the elements of the array and sum them. I don’t know why but it just takes the first 6 variables. What do I need to do?

function range(start, end) {
  let arr = []

  for (let i = start; i <= end; i  ) {
    arr.push(i)
  }

  return arr
}

let arr = range(1, 10)

function sum() {
  let g = 0;

  for (let i = 0; i <= arr.length; i  ) {
    g  = arr.shift()
  }

  return g
}

console.log(sum())

CodePudding user response:

In your sum function -

function sum() { // ❌ no input parameter
  let g = 0;

  for (let i = 0; i <= arr.length; i  ) { // ❌ i will go out of bounds
    g  = arr.shift() // ❌ arr.shift modifies the length of arr
  }

  return g
}

Let's see what happens given a concrete example arr -

const arr = [1,2,3,4,5,6,7,8,9]

for (let i = 0; i <= arr.length; i  ) {
  g  = arr.shift()
}
i arr i <= arr.length arr.shift() g
0 [1,2,3,4,5,6,7,8,9] true 1 1
1 [2,3,4,5,6,7,8,9] true 2 3
2 [3,4,5,6,7,8,9] true 3 6
3 [4,5,6,7,8,9] true 4 10
4 [5,6,7,8,9] true 5 15
5 [6,7,8,9] false exit loop 15 ❌

As you can see, i exceeds the length of the array after the halfway point has been reached. g is only equal to the sum of the first half. To fix it, don't modify the array inside the loop -

function sum(arr) { // ✅ input parameter
  let g = 0;

  for (let i = 0; i < arr.length; i  ) { // ✅ use <
    g  = arr[i] // ✅ arr[i] reads element, doesn't modify arr
  }

  return g
}
i arr i < arr.length arr[i] g
0 [1,2,3,4,5,6,7,8,9] true 1 1
1 [1,2,3,4,5,6,7,8,9] true 2 3
2 [1,2,3,4,5,6,7,8,9] true 3 6
3 [1,2,3,4,5,6,7,8,9] true 4 10
4 [1,2,3,4,5,6,7,8,9] true 5 15
5 [1,2,3,4,5,6,7,8,9] true 6 21
6 [1,2,3,4,5,6,7,8,9] true 7 28
7 [1,2,3,4,5,6,7,8,9] true 8 36
8 [1,2,3,4,5,6,7,8,9] true 9 45
9 [1,2,3,4,5,6,7,8,9] false exit loop 45 ✅
  • Related