简体   繁体   English

如何将 0 添加到 javascript 的数组中?

[英]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我正在尝试使用上面的代码片段生成 1 到 12 之间的数字我得到了结果

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

like this But I want output something like this像这样但我想要 output 像这样

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

how to achieve output like this.如何像这样实现 output。

this is my range function这是我的范围 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 const array = [...Array(13).keys()] // 创建从 0 到 13 的数组 array.shift() // 删除数组的第一个元素,这对我们来说是 0 不需要的元素 const months = array. map(month => month >= 10? month: '0'+month) // 检查数组的每个值,如果值大于或等于 10,我们将其加 0

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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