旋转数组并将所有组合存储在对象变量中

时间:2017-11-22 17:33:56

标签: javascript arrays

我有月份数组,应该将旋转到一段时间。将所有旋转数组存储在对象变量中。能否请您提出更有效的方法。

var Month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];


 Output looks like:

 monthRotate = {
                      rotate1: ["Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"],
                      rotate2: ["Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb"],
                       .
                       .
                       . 
                       .
                      rotate11: ["Dec", "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov"]; 
             }

我已尝试过以下方法。

var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var rotate = {};
for (var i=1;i<months.length;i++){
	var mts = months.slice(i).concat(months.slice(0,i));
	rotate["rotate"+i] = mts;
}

console.log(rotate);

2 个答案:

答案 0 :(得分:2)

您可以使用shift方法删除给定array的第一个元素,然后在数组的末尾推送

var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
let final = [...Array(months.length-1)].reduce(function(arr){
   months.push(months.shift());
   arr.push([...months]);
   return arr;
},[]);
console.log(final);

答案 1 :(得分:1)

您可以通过以下方式创建rotations数组对象:

var Month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
var rotations = [];
for(var i = 0; i < 11; i++){
    rotations[i] = [];
   for(var j = i+1, k = 0; k < 12; j++, k++){
      if(j === 12){
         j = 0;
      } 
      rotations[i].push(month[j]);
   }
}

控制台输出: enter image description here