颜色分为16进制和,rgba两种.首先我们可以定义一个函数,函数默认形参可以使用flag.
function getColor(flag = true) { } **1.定义了这个函数以后我们可以想到,这里面是两种情况,一种用16进制,一种用rgba,这个判断可以用三元判断也可以使用if语句判断 **
2.这里我们采用if语句
function getColor(flag = true) { if(flag){ return16进制 }else{ returnrgba(?,?,?) } }
**3.我们可以先进行else里面的判断可以使用math.random来获取0到255之间的数字, 方法就是 例如 let num = Math.floor(Math.random() * 256).使用floor是为了向下取整数.这样操作可以获得0到255之间的,随机生成的数字且是整数
else{ let r = Math.floor(Math.random() * 256) let g = Math.floor(Math.random() * 256) let b = Math.floor(Math.random() * 256) return rgba({g},${b}) }
接下来我们可以做什么if里面的板块了 1.首先我们先声明一个字符串就是'#'号,因为每一个16进制的开头都是他 2.我们声明一个数组,就是16进制的数字和字母集合 3.可以通过for循环使每次str加上一个新的随机生成的数字或者字母,这里由于后面用六位数我们则循环六次
if (flag) {
let str = `#`
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
-
每次循环过程中,我们都采用一个random随机生成的数字作为数组的下标 * for (i = 1; i <= 6; i++) { let random = Math.floor(Math.random() * arr.length) str = str + arr[random] } return str ** 最后我们输出 return str **
整理下来全部过程如下
<script> function getColor(flag = true) { if (flag) { let str =# let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] for (i = 1; i <= 6; i++) { let random = Math.floor(Math.random() * arr.length) str = str + arr[random] } return str } else { let r = Math.floor(Math.random() * 256) let g = Math.floor(Math.random() * 256) let b = Math.floor(Math.random() * 256) returnrgba({g},${b}) } } console.log(getColor()); console.log(getColor(false)); </script>