不重复随机数
<body>
<button>开始</button>
<p></p>
<script>
//求20--100之间10个不重复的随机数
var op = document.querySelector('p')
var btn = document.querySelector('button')
var arr = []
function sjs(x){
for(i=0;i<x;i++){
var shu = Math.floor(Math.random()*(100-20)+20)
if(arr.indexOf(shu) == -1){
arr.push(shu)
return arr
}else{
i--
}
}
}
console.log(arr)
btn.onclick = function(){
op.innerHTML = sjs(10)
}
</script>
</body>
验证码
<body>
<script>
var str = '1234567890qwertyuiopasdfghjklzxcvbnmQWRTYUIOPASGHJKLZXBNM'
var len = str.length
var yzm = '';
var arr = []
for(var i=0;i<4;i++){
var x = Math.floor(Math.random()*len);
// yzm += str.charAt(x)
yzm += str[x]
// arr.push(str.charAt(x) )
}
console.log(yzm)
console.log(typeof yzm)
console.log(arr)
console.log(typeof arr)
</script>
</body>
//或者
<body>
<span></span><button>换一个</button>
<script>
var span = document.querySelector('span')
var btn = document.querySelector('button')
function random(x){
var str = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'
var arr = str.split('')
console.log(arr)
var newArr = []
for(i=0;i<x;i++){
newArr[i] = (arr[Math.floor(Math.random()*arr.length)])
}
console.log(typeof newArr)
var num = newArr.join('')
return num
}
btn.onclick = function(){
span.innerHTML = random(4)
}
</script>
</body>