Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ย้าย N ตัวท้ายอาร์เรย์มาหน้าสุดใน JavaScript

สมมติว่าเราต้องเขียนฟังก์ชันอาร์เรย์ prependN() ที่รับตัวเลข n (n <= ความยาวอาร์เรย์) และนำ n องค์ประกอบจากท้ายมาไว้หน้าอาร์เรย์

เราต้องทำแบบ in-place และฟังก์ชันควรคืนค่า boolean ตามว่าทำสำเร็จหรือล้มเหลว

ตัวอย่างเช่น:

// หากอาร์เรย์อินพุตคือ:
const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"];
// และ n คือ 3
// อาร์เรย์ควรเปลี่ยนเป็น:
const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"];
// และคืนค่า 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']