【问题标题】:Return array backwards from current month从当前月份向后返回数组
【发布时间】:2020-05-15 18:05:47
【问题描述】:

现在是一月。

  var d = new Date();
  var m = d.getMonth();

console.log(m) 会输出 0;

我有一个数组:

var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

我想返回过去 4 个月。从当月开始。所以在这种情况下。 一月、十二月、十一月、十月 我怎样才能做到这一点?

var monthSliced = months.slice(m, m4).reverse();

返回:["Apr", "Mar", "Feb", "Jan"] 有什么想法吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:
    var currentDate = new Date();
    var currentMonth = currentDate.getMonth();
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var result = [];
    
    
    function getPreviousMonths(month, count) {
        if(count > 3) return;
        if(month === -1) month = 11;
        result.push(months[month])
        getPreviousMonths(--month, ++count)
    }
    
    getPreviousMonths(currentMonth, 0, [])
    console.log(result)
    

    【讨论】:

      【解决方案2】:

      一种方法是这样的:

      const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      const currentMonth = new Date().getMonth();
      const result = [];
      
      for(let i = currentMonth; i > currentMonth - 4; i--) {
        result.push(months[(months.length + i) % months.length]);
      }
      
      console.log(result);

      【讨论】:

        【解决方案3】:

        你可以循环四次,每次循环,你可以使用months.slice(m).shift()从你的数组中获取一个元素。使用这种检索方法将允许您输入负索引并从数组末尾检索元素:

        const d = new Date();
        let m = d.getMonth();
        const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
        
        const result = [];
        for(let i = 0; i < 4; (i++, m--)) {
          result.push(months.slice(m).shift());
        }
        console.log(result);

        【讨论】:

          猜你喜欢
          • 2016-02-29
          • 1970-01-01
          • 1970-01-01
          • 2018-06-23
          • 1970-01-01
          • 1970-01-01
          • 2019-08-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多