ES6 - generate an array of numbers

前端 未结 6 715
我寻月下人不归
我寻月下人不归 2021-01-31 08:03

Having googled for it I found two solutions:

6条回答
  •  孤城傲影
    2021-01-31 08:39

    Here is a range function which takes start, end, and a step parameter. It returns an array starting a from start upto (but excluding) the end number with increments of size step.

    const range = (start, end, step) => {
      return Array.from(Array.from(Array(Math.ceil((end-start)/step)).keys()), x => start+ x*step);
    }
    
    console.log(range(1, 10, 1));
    //[1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    console.log(range(0, 9, 3));
    //[0, 3, 6]
    
    console.log(range(10, 30, 5));
    //[10, 15, 20, 25]

    Taking a step further, if you want a range that includes the end as well.

    const inclusiveRange = (start, end, step) => {
      return Array.from(Array.from(Array(Math.ceil((end-start+1)/step)).keys()), x => start+ x*step);
    }
    
    console.log(inclusiveRange(1, 10, 1));
    //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    console.log(inclusiveRange(0, 9, 3));
    // [0, 3, 6, 9]
    
    console.log(inclusiveRange(10, 30, 5));
    //[10, 15, 20, 25, 30]

提交回复
热议问题