NeteaseStudy / frontend-edu

前端学习资料&问答汇总
https://study.163.com/smartSpec/intro.htm
Other
26 stars 8 forks source link

如何通过十六进制,每次随机生成一个不同的背景色 #1

Open triboby opened 5 years ago

triboby commented 5 years ago

今天碰到个面试题 如何通过十六进制,每次随机生成一个不同的背景色,要求生成100个不重复,且不遍历比较

lengmeiyanok commented 4 years ago

// 生成不同类型的颜色

var sixArr = new Array(6).fill(0) console.log(sixArr) var hundredColor = [] function produceColor() { let colorVal = '#' sixArr.forEach(() => { colorVal += Math.floor(Math.random() * 16).toString(16) }) return colorVal } do { let newColorVal = produceColor() let index = hundredColor.findIndex(() => { return === newColorVal }) if (index === -1) { hundredColor.push(newColorVal) } } while (hundredColor.length < 101) console.log(hundredColor)

haoran12138 commented 4 years ago

let colorList = new Set();

function getRandomColor() { let color = parseInt(Math.random() * (16777215 + 1), 10).toString(16); return "#" + color.padStart(6, "0"); } while (true) { colorList.add(getRandomColor()); if (colorList.size >= 10) { break; } } console.log(colorList);

haoran12138 commented 4 years ago

// 生成不同类型的颜色

var sixArr = new Array(6).fill(0) console.log(sixArr) var hundredColor = [] function produceColor() { let colorVal = '#' sixArr.forEach(() => { colorVal += Math.floor(Math.random() * 16).toString(16) }) return colorVal } do { let newColorVal = produceColor() let index = hundredColor.findIndex(() => { return === newColorVal }) if (index === -1) { hundredColor.push(newColorVal) } } while (hundredColor.length < 101) console.log(hundredColor)

遍历比较了