- 使用
slice
[1,2,3,4,5,6,7]
向右移动 3 步的结果为[5, 6, 7, 1,2, 3, 4]
function rotateArray(arr, k){
const len = arr.length
if(k < 0 || k === 0 || k === len) return arr
if(k > len) k = k % len
return arr.slice(-k).concat(arr.slice(0, arr.length-k))
// return [...arr.splice(len - k), ...arr]
}
const arr = [1,2,3,4,5,6,7]
console.log(rotateArray(arr,-1)) // [1,2,3,4,5,6,7]
console.log(rotateArray(arr,0)) // [1,2,3,4,5,6,7]
console.log(rotateArray(arr,7)) // [1,2,3,4,5,6,7]
console.log(rotateArray(arr,3)) // [5, 6, 7, 1,2, 3, 4]
arr.slice()
可以接收负数索引,从倒数第n个值开始截取
- 使用
pop
和unshift
进行移动模拟
频繁的移动数组,效率很差
function rotateArray(arr, k){
const len = arr.length
if(k < 0 || k === 0 || k === len) return arr
for (let index = 0; index < k; index++) {
arr.unshift(arr.pop())
}
return arr
}
function rotateArray(arr, k){
const len = arr.length
if(k < 0 || k === 0 || k === len) return arr
new Array(k).fill('').forEach(() => arr.unshift(arr.pop()))
return arr
}