gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 04:22:16 26 4
gpt4 key购买 nike

我有月份数组,它的长度应该从left 旋转到right。将所有旋转数组存储在对象变量中。您能否建议更有效的方法。

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

最佳答案

您可以使用shift 方法删除给定数组 的第一个元素,然后将其压入 < strong>数组。

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

关于javascript - 旋转数组并将所有组合存储在对象变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47440772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com