如何在TypeScript中实现从索引位置反向循环数组?

问题描述 投票:0回答:3

我想使用 typescript 获取当前月份的最后 12 个月的数据。

假设当前月份是七月,那么我的输出应该是 ['八月','九月','十月','十一月','十二月','一月','二月','三月','四月','五月','六月','七月']

假设我的数组是 let myarr=['a','b','c','d'] 并且我想要索引位置 2 的数据,那么输出数组应该是 ['c','b','a ','d'].

arrays typescript reverse circular-dependency
3个回答
0
投票

//Use below code snippet as arr is your array and N  index position from where //need to reverse data on graph x axis + 1
reverseCircularArray(arr: any, N: number) {
  //initialise 2 array
  let firstArr = arr.slice(0, N);
  let secondArr = arr.slice(N);

  // return the circular array
  return [...secondArr, ...firstArr];
}


0
投票

您可以使用模数 % 运算符来完成此操作

const months = ["Jan", "Feb", "Mar", "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const arr = [];
const startMonth = 7;//Aug index

for (let i = 0; i < 12; ++i){
   arr.push(months[(i+startMonth) % months.length]);
}
console.log(arr);

0
投票

const months = ["Jan", "Feb", "Mar", "Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
const arr = [];
const startMonth = 7;//August index

for (let i = 0; i < 12; ++i){
   arr.push(months[(i+startMonth) % months.length]);
}
console.log(arr);

© www.soinside.com 2019 - 2024. All rights reserved.