旋转数组 - JavaScript

javascriptweb developmentobject oriented programmingfront end technology更新于 2025/11/24 10:20:17

假设,我们需要编写一个 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
]

相关文章


有用资源