简体   繁体   中英

Why is my function working when called by itself but not when I call it with another function? (Beginner javascript question)

I am working on some coding challenges (I am still a beginner). I was able to make both of these functions work, but when I try to call them together my second function just returns zero..

Both functions take in two parameters (or more). The first function counts the numbers between the two paramters and returns them in a string (1, 5) => [1,2,3,4,5] and the second sums them together (1,10) => 55. Any reason why these work individually but not together?

Thanks in advance!

`let range = (start, end) => {
    numbers = [];
    for(i = start; i<end+1; i++) {
      if(i>=start){
      numbers.push(i);
        if (i>=end) {
          console.log(numbers);
        }
      }
    }

}

function sum(start, ...add){ 
    let sumCounter = 0; 
      for(i = start; i<=add; i++) {
        sumCounter += i;
    }
    return sumCounter;
} 

console.log(sum(1,10)); //second function works

console.log(sum(range(1, 10))); //first function works, not second function `

There are a lot of things going on here. First make sure that you're returning a value in the first function, and not just printing to the console. Second, when you say “if(i>=end)” that will always be true, so it isn't needed. Also instead of saying “if(I>=end)” you can put “I==end” or just put the following code after the for loop. I would suggest that you return the numbers, and take that as a parameter for your sum function. I hope you're able to follow all of that!

Here is a working option:

function range(start, end) {
    var numbers = [];
    for (i=start;i<end+1;i++) {
        numbers.push(i)
    } 
    return numbers;
}

console.log("Sum: " + range(5, 10).reduce((a,b) => a + b, 0));

Or this might be easier to understand:

function range(start, end) {
    var numbers = [];
    for (i=start;i<end+1;i++) {
      numbers.push(i)
    } 
    return numbers;
}

function sum(nums) {
    var sum = 0;
    for (i=0;i<nums.length;i++) {
        sum += nums[i];
    }
    return sum;
}

console.log("Sum: " + sum(range(5, 10)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM