Looping range, step by step?

前端 未结 2 926
夕颜
夕颜 2020-12-22 15:19

I am trying to define a function range which takes 3 integer parameters: start, end, and step.

The function should return an array of numbers from start to end count

相关标签:
2条回答
  • 2020-12-22 15:52

    Your for loop isn't doing anything. In particular, it's not creating an array. You're just trying to return the 3 inputs, not the array of numbers that's supposed to be generated. But since you're combining them with the comma operator, you just return the last parameter (see What does a comma do in JavaScript expressions?).

    Your loop needs a body that adds the current element to an array.

    const range = function(start, end, step) {
      const result = []
      for (let i = start; i <= end; i += step) {
        result.push(i);
      }
      return result;
    }
    
    console.log(range(0, 10, 2));

    0 讨论(0)
  • 2020-12-22 15:54

    Create an array and use your existing for loop to push the values to that array andthen return the array. I have given both a for loop and a while loop that gets the job done.

    // using a for loop
    const range = function(start, end, step) {
      let arr = [];
      for (i = start; i <= end; i += step){
         arr.push(i);
      };
      return arr;
    }
    
    console.log("Using a for loop: ", range(0, 10, 2)); // gives [ 0, 2, 4, 6, 8, 10]
    
    // using a while loop
    const range2 = function(start, end, step) {
      let arr = [];
      let i = start
      while (i <= end){
         arr.push(i); 
         i += step;
      };
      return arr;
    }
    
    console.log("Using a while loop: ", range2(0, 10, 2)); // gives [ 0, 2, 4, 6, 8, 10]

    0 讨论(0)
提交回复
热议问题