随机按钮
赞
踩
点击按钮实现数组采集5个10以内的随机数(不包含10)
主要思路:
1.随机数的采集,因为可能存在重复现象,所以并不确定随机多少次能采集到5个不重复的数字,故使用while循环
2.创建空数组,J将每次循环产生的随机数与数组比较,没有就添加进来,当数组采集够5个数,循环结束,输出数组
-
- <body>
- <button onclick="get_random(0,10)">随机按钮</button>
- <script>
- // 随机生成5个 不重复的(0-10之间,不包含10的)整数 存入数组
- let arr = [];
- function get_random(start,end) {
- while(arr.length<5){
- let num = Math.floor(Math.random()*(end-start)+start);
- if (arr.indexOf(num) == -1) {
- arr.push(num);
- }
- }
- console.log(arr);
- return arr;
- }
- </script>
- </body>

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。