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

JavaScript ลบรายการสุ่มจากอาร์เรย์ แล้วลบซ้ำจนอาร์เรย์ว่าง

เราได้รับอาร์เรย์สตริง/ตัวเลขลิเทอรัล ต้องสร้างฟังก์ชัน removeRandom() รับอาร์เรย์ ลบรายการสุ่มหนึ่งรายการออกจากอาร์เรย์และพิมพ์พร้อมกันแบบ recursive จนอาร์เรย์ว่าง

ทำได้โดยสร้างตัวเลขสุ่มด้วย Math.random() ลบรายการที่ index นั้นด้วย Array.prototype.splice() พิมพ์ ทำซ้ำจนความยาวอาร์เรย์เหลือ 0

โค้ด

ตัวอย่าง

const arr = ['Arsenal', 'Manchester United', 'Chelsea', 'Liverpool', 'Leicester City', 'Manchester City', 'Everton', 'Fulham', 'Cardiff City'];
const removeRandom = (array) => {
  while(array.length){
    const random = Math.floor(Math.random() * array.length);
    const el = array.splice(random, 1)[0];
    console.log(el);
  }
};
removeRandom(arr);

ผลลัพธ์ในคอนโซลอาจเป็น

หมายเหตุ - เนื่องจากเป็นสุ่ม ผลลัพธ์อาจต่างทุกครั้ง นี่เป็นเพียงหนึ่งในหลายผลลัพธ์ที่เป็นไปได้

ผลลัพธ์

Leicester City
Fulham
Everton
Chelsea
Manchester City
Liverpool
Cardiff City
Arsenal
Manchester United