Posted in Javascript onDecember 07, 2018
本文实例讲述了JS实现随机生成10个手机号的方法。分享给大家供大家参考,具体如下:
JS部分:
<script> function getMoblieNum(){ var numArray = new Array("139","138","137","136","135","134","159","158","157","150","151","152","188","187","182","183","184","178","130","131","132","156","155","186","185","176","133","153","189","180","181","177"); //这是目前找到的除了数据卡外的手机卡前三位,类型是字符串数组 var numList = ""; //创建一个数组用来存放10个手机号 var arraryLength = numArray.length; //获取数组长度,这样如果手机号前三位取值单位发生变化,在下一步求i的地方就不用修改随机数取值范围了 for( var n = 0; n < 10; n++){ var i = parseInt( Math.random() * arraryLength); //注意乘以的是上面numArray数组的长度,这样就可以取出数组中的随机一个数。random的取值范围是大于等于0.0,小于1.0,相乘后得到的就是0到(数组长度-1)的值。 var num = numArray[i]; //取出随机的手机号前三位并赋值给num,手机号前三位是字符串类型的 for ( var j = 0; j < 8; j++){ num = num + Math.floor(Math.random() * 10); //num是字符串,后面的数字被当做字符串。所以变成两个字符串拼接了 } if(n == 0){ numList = numList + num; //第一个手机号前不出现“,” } else{numList = numList + "," + num;} //从第一个手机号后面到最后一个之前用逗号分隔 } var numSpan = document.getElementById("moblieNum"); numSpan.innerHTML = numList; //修改span的内容,每次都是清空修改,而不是叠加 } </script>
HTML部分:
<input type='button' value='随机生成10个电话号码' onclick='getMoblieNum()' /><br/> 电话号码:<div id='moblieNum'></div>
感兴趣的朋友可使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun ,或 在线HTML/CSS/JavaScript前端代码调试运行工具:http://tools.3water.com/code/WebCodeRun测试运行上述代码,可得到如下运行结果:
JS实现随机生成10个手机号的方法示例
- Author -
yytoo2声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@