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

后端 未结 15 1774
耶瑟儿~
耶瑟儿~ 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:28

    You could use a single for loop, while loop , Array.prototype.map(), Array.prototype.concat() , String.prototype.replace()

    var n = 0,
      min = 5,
      periods = [" AM", " PM"],
      times = [],
      hours = [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
    
    for (var i = 0; i < hours.length; i++) {
      times.push(hours[i] + ":" + n + n + periods[0]);
      while (n < 60 - min) {
        times.push(hours[i] + ":" + ((n += 5) < 10 ? "O" + n : n) + periods[0])
      }
      n = 0;
    }
    
    times = times.concat(times.slice(0).map(function(time) {
      return time.replace(periods[0], periods[1])
    }));
    
    console.log(times)

提交回复
热议问题