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

สร้างสีสุ่มใน JavaScript

เราต้องเขียนฟังก์ชัน JavaScript ชื่อ randomColor ที่คืนค่าสี hex แบบสุ่มทุกครั้งที่เรียก

ตัวอย่าง

โค้ดต่อไปนี้เป็นตัวอย่าง:

const randomColor = () => {
  let color = '#';
  for (let i = 0; i < 6; i++){
    const random = Math.random();
    const bit = (random * 16) | 0;
    color += (bit).toString(16);
  };
  return color;
};

console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());
console.log(randomColor());

ผลลัพธ์

จะแสดงผลในคอนโซลดังนี้:

#762b46 #cfa0bf #a20ee1 #c2f7e0 #5d5822 #380f30 #805408