เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่สร้างอาร์เรย์ของตัวเลขสุ่มที่ไม่ซ้ำกันห้าตัวพอดี เงื่อนไขคือตัวเลขทั้งหมดต้องอยู่ในช่วง [0, 9] และหมายเลขแรกไม่สามารถเป็น 0 ได้
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const fiveRandoms = () => {
const arr = []
while (arr.length < 5) {
const random = Math.floor(Math.random() * 10);
if (arr.indexOf(random) > -1){
continue;
};
if(!arr.length && !random){
continue;
}
arr[arr.length] = random;
}
return arr;
};
console.log(fiveRandoms()); ผลลัพธ์
สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ในคอนโซล -
[ 9, 0, 8, 5, 4 ]