將給定陣列的最後 n 個元素移動到陣列前面 JavaScript
假設我們必須編寫一個數組函式,設為 prependN(),它接受一個數字 n(n <= 使用該函式的陣列的長度),從末尾取 n 個元素並將它們放在陣列前面。
我們必須就地完成此操作,並且該函式應該僅根據任務的成功完成或失敗返回一個布林值。
例如 −
// if the input array is: const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; // and the number n is 3, // then the array should be reshuffled like: const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]; // and the return value of function should be true
現在,讓我們為此函式編寫程式碼 −
示例
const arr = ["blue", "red", "green", "orange", "yellow", "magenta",
"cyan"];
Array.prototype.reshuffle = function(num){
const { length: len } = this;
if(num > len){
return false;
};
const deleted = this.splice(len - num, num);
this.unshift(...deleted);
return true;
};
console.log(arr.reshuffle(4));
console.log(arr);輸出
控制檯中的輸出為 −
true [ 'orange', 'yellow', 'magenta', 'cyan', 'blue', 'red', 'green' ]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP