var str ='0123456789abcdef'// 字符串中的每一个字符都是十六进制的取值// 写法1functiongetColor1(){var color ='#'for(var i =0; i <6; i++){// 获取随即索引var index = Math.floor(Math.random()* str.length)
color += str[index]}return color
}// 写法2:先获取0~255随机整数再转换成十六进制functiongetColor2(){var color ='#'for(var i =0; i <3; i++){// 获取0~255随机整数var n = Math.floor(Math.random()*256)
color += n >15? n.toString(16):'0'+ n.toString(16)}return color
}
获取四位随机不重复的字符验证码
var str ='qwertyuiopasdfghjklzxcvbnm1234567890'var code =''// 验证码// 使用for循环for(var i =0; i <4; i++){// 获取随机索引(0 ~ str.length-1)var index =getRandom(0, str.length -1)// 获取随机字符var s = str.charAt(index)// 拼接随机字符,如果获取的随机字符s在code中已经存在则i--
code.includes(s)? i--: code += s
}
console.log(code)