简体   繁体   English

如何从一系列月份对象[{month:'Jan'id:'1},{month:'Feb',id:'2},…{month:'Dec',id :12}]?

[英]How to get next 4 months from current month in an array of month objects [{month:'Jan' id:'1},{month:'Feb', id:'2},…{month:'Dec', id:12}]?

I tried array slice but its not giving expected result if starting month is one of the last 3 months of the year. 我尝试了数组切片,但是如果开始月份是一年的最后三个月之一,则无法给出预期的结果。

If current month is November then its should give November to February list 如果当前月份是11月,则应给出11月至2月的清单

Simply double the array and then slice it 只需将数组加倍然后切成薄片

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

Demo 演示版

 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 ); 

If spread ... is not supported, then use concat 如果不支持传播... ,则使用concat

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

A lengthy approach but works. 冗长的方法,但是有效。

 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) 

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

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