旋转数组-JavaScript
假设我们需要编写一个JavaScript函数,该函数接受一个数组和一个数字n并将数组旋转n个元素
例如:如果输入数组是-
const arr = [12, 6, 43, 5, 7, 2, 5];
n是3
那么输出应该是-
const output = [5, 7, 2, 5, 12, 6, 43];
让我们为该函数编写代码-
示例
以下是代码-
// rotation
const arr = [12, 6, 43, 5, 7, 2, 5];
const rotateByOne = arr => {
for(let i = 0; i < arr.length-1; i++){
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
};
}
Array.prototype.rotateBy = function(n){
const { length: l } = this;
if(n >= l){
return;
};
for(let i = 0; i < n; i++){
rotateByOne(this);
};
};
const a = [1,2,3,4,5,6,7];
a.rotateBy(2);
console.log(a);输出结果
以下是控制台中的输出-
[ 3, 4, 5, 6, 7, 1, 2 ]