Generate array of times (as strings) for every X minutes in JavaScript

后端 未结 15 1779
耶瑟儿~
耶瑟儿~ 2020-12-24 01:46

I\'m trying to create an array of times (strings, not Date objects) for every X minutes throughout a full 24 hours. For example, for a 5 minute interval the arr

15条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-24 02:06

    Loops are unnecessary in this case.

    ES6

    //Array.from, only supported by Chrome 45+, Firefox 32+, Edge and Safari 9.0+
    //create an array of the expected interval
    let arr = Array.from({
      length: 24 * 60 / 5
    }, (v, i) => {
      let h = Math.floor(i * 5 / 60);
      let m = i * 5 - h * 60;
      //convert to 12 hours time
      //pad zero to minute
      if (m < 10) {
        m = '0' + m;
      }
      let label = 'AM';
      if (h > 12) {
        label = 'PM';
        h -= 12;
      }
      if (h === 0) {
        h = 12;
      }
      return h + ':' + m + ' ' + label;
    });
    
    document.body.textContent = JSON.stringify(arr);

    Wider browser support

    var arr = Array.apply(null, {
      length: 24 * 60 / 5
    }).map(function(v, i) {
      var h = Math.floor(i * 5 / 60);
      var m = i * 5 - h * 60;
      if (m < 10) {
        m = '0' + m;
      }
      var label = 'AM';
      if (h > 12) {
        label = 'PM';
        h -= 12;
      }
      if (h === 0) {
        h = 12;
      }
      return h + ':' + m + ' ' + label;
    });
    
    document.body.textContent = JSON.stringify(arr);

提交回复
热议问题