FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

实现输出一个十六进制的随机颜色(#af0128a)

Open lgwebdream opened this issue 5 years ago • 5 comments

lgwebdream avatar Jul 06 '20 15:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 15:07 lgwebdream

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getColor() {
    let result = new Array(6)
    let i = 0
    let hexMap = ['a', 'b', 'c', 'd', 'e', 'f']
    while (i < 6) {
        let data = getRandomInt(0, 16)
        result[i] = data > 10 ? hexMap[data % 10] : data

        i++
    }
    return `#${result.join('')}`
}

yulishuta avatar Feb 15 '21 03:02 yulishuta

function randomColor() {
    const r = (Math.floor(Math.random() * 255)).toString(16);
    const g = (Math.floor(Math.random() * 255)).toString(16);
    const b = (Math.floor(Math.random() * 255)).toString(16);
    const a = (Math.random()).toString(16).slice(2, 4);
    console.log(a);
    return `#` + r + g + b + a;
  }

qzruncode avatar Apr 17 '21 09:04 qzruncode

// 实现输出一个十六进制的随机颜色(#af0128a)
let color = '#' + parseInt(Math.random() * 0x1000000).toString(16).padStart(6, '0')
console.log(color);

dty999 avatar Jul 07 '21 13:07 dty999

var colorStr = '#';
function randomColor() {
    var items = [0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
    var index = Math.floor(Math.random()*15);
    return items[index];
} 
for (let i = 0; i < 6; i++) {
    colorStr += randomColor();
}

ZhuJingLe avatar Feb 15 '22 08:02 ZhuJingLe