简体   繁体   中英

how to add the 0 to the the array in javascript?

  var months = range(1, 12);

I am trying to generate numbers between 1 to 12 by using above snippet I am getting the result

[   {
        label: '1',
        value: '1',
    },
    {
        label: '2',
        value: '2',
    },   .....  {
        label: '12',
        value: '12',
    }, ]

like this But I want output something like this

  [   {
        label: '01',
        value: '01',
    },
    {
        label: '02',
        value: '02',
    },   .....  {
        label: '12',
        value: '12',
    }, ]

how to achieve output like this.

this is my range function

function range(start, end) {
        return Array(end - start + 1)
            .fill()
            .map((_, idx) => ({
                label: start + idx,
                value: start + idx,
            }));
    }

const array = [...Array(13).keys()] // creating array from 0 to 13 array.shift() // deleting the first element of an array which is 0 unwanted element for us const months = array.map(month => month >= 10? month: '0'+month) // checks every value of the array if value is greater or equals to 10, we add 0 to it

Try this

function range (start, end) { 
  const arr = [];
  for(var i = start; i<=end; i++) {
    const value = i.toString().padStart(2, '0');
    arr.push({label: value, value});
  }
  return arr;
}

Usage

range(1,12)

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