旋转数组 - 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 ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP