由于在做业务的时候需要对数组每个元素的位置进行有规律的频繁顺移(朝前后移动任意数位),所以封装了一个简单的方法,需要的自取即可。
设定:有一个数组 :
let arr1 = [ '1','2','3','4','5']
要求:使其每个元素向前(后)各移动2位,即:
arr1 = ["4", "5", "1", "2", "3"]; //向后(右)移动2位
arr1 = ["3", "4", "5", "1", "2"]; //向前(左)移动2位
实现方法(代码):
//向前移动(右)
let forWardTo = (arr, length) => {
let arr2 = [...arr]
if (length > arr2.length) {
length = length % arr2.length
}
// let LastIndex = arr[arr.length - 1];
// let LastIndex2 = arr[arr.length - 2];
let CuttedArray = []
for (let i = 1; i <= length; i++) {
CuttedArray.unshift(arr2[arr2.length - 1])
arr2.pop()
}
let NewArray = [...CuttedArray, ...arr2]
return NewArray
}
//向后移动(左)
let BackTo = (arr, length) => {
let arr2 = [...arr]
if (length > arr2.length) {
length = length % arr2.length
}
let CuttedArray = []
for (let i = 0; i < length; i++) {
CuttedArray.push(arr2[0])
arr2.shift()
}
let NewArray = [...arr2, ...CuttedArray]
return NewArray
}
console.log(forWardTo(arr1,2))或者console.log(BackTo(arr1,2))就可以看到返回的结果了。
哦,由于最后结果是返回新数组,可以直接链式数组的方法。