如何在月份对象数组中从当月开始接下来的4个月[{month:'Jan'id:'1},{month:'Feb',id:'2},... {month:'Dec' ,id:12}]?

时间:2018-03-09 05:19:30

标签: javascript arrays slice

我尝试了数组切片,但如果开始月份是一年中的最后3个月之一,那么它没有给出预期的结果。

如果当前月份是11月,那么它应该给出11月到2月的列表

2 个答案:

答案 0 :(得分:2)

只需将数组加倍然后将其切片

var newArr = [ ...arr, ...arr ];
var index = 10;
var output = newArr.slice( index, index + 4 )

<强>演示

var arr = [{
  month: 'Jan',
  id: "1"
}, {
  month: 'Feb',
  id: "2"
}, {
  month: 'Mar',
  id: "3"
}, {
  month: 'Apr',
  id: "4"
}, {
  month: 'May',
  id: "5"
}, {
  month: 'Jun',
  id: "6"
}, {
  month: 'Jul',
  id: "7"
}, {
  month: 'Aug',
  id: "8"
}, {
  month: 'Sep',
  id: "9"
}, {
  month: 'Oct',
  id: "10"
}, {
  month: 'Nov',
  id: "11"
}, {
  month: 'Dec',
  id: "12"
}];

var newArr = [ ...arr, ...arr ];
//console.log( newArr );
var index = 10;
var output = newArr.slice(index, index+4);

console.log( output );

如果不支持展开...,请使用concat

var newArr = arr.concat(arr.slice())

答案 1 :(得分:0)

漫长的方法,但有效。

&#13;
&#13;
let months = ['Jan','Feb', 'Mar', 'Apr', 'May' ,'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']


let currMonth_id = new Date().getMonth();

let output = [];
output.push({month: months[currMonth_id], id: currMonth_id+1});

for(let i = 1 ; i < 4; i++) {
  let nextMonth_id = (currMonth_id + i) % 12; 
  output.push({month: months[nextMonth_id], id: nextMonth_id+1});
}

console.log(output)
&#13;
&#13;
&#13;