javascript生成指定位数的随机数

yfisaboy 2020-01-19

<script type="text/javascript">

		document.write("请输入要生成随机数的位数:");
			// digit是数字的位数
			function runStr(digit){
				if(digit=="" || isNaN(digit)){
					alert("请输入数字");
				}else{
					var sourceStr="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G";
					arrStr=sourceStr.split(",");
					var result=""; //定义变量并初始化
					var index=0;
					for(i=0;i<digit;i++){
						index=parseInt(Math.random()*arrStr.length);
						result+=arrStr[index];
					}
					alert(result);
				}

			}


		</script>

		<form name="form">
			<input type="text" name="digit"/>
			<input type="button" value="生成" onClick="runStr(form.digit.value)">
		</form>

相关推荐