Viết phương thức mảng prependN() nhận số n (n ≤ độ dài mảng), lấy n phần tử cuối đưa lên đầu mảng tại chỗ, trả về boolean thành công/thất bại.
Ví dụ:
// Input: ['blue', 'red', 'green', 'orange', 'yellow', 'magenta', 'cyan'], n=3// Output: ['yellow', 'magenta', 'cyan', 'blue', 'red', 'green', 'orange']
Ví dụ
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);Kết quả
Đầu ra trong console sẽ là:
true[ 'orange', 'yellow', 'magenta', 'cyan', 'blue', 'red', 'green' ]