Looping range, step by step?

前端 未结 2 943
夕颜
夕颜 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: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]

提交回复
热议问题