สมมุติว่าเราต้องเขียนฟังก์ชัน 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 ]