求教一个JS问题,代码如下,为什么有时回返回undefined啊。。。
这是一个生成几个随机数的方法,ramcount是生成的个数,max生成范围上限<script>functionnumbers(ramcount,max){varflag=...
这是一个生成几个随机数的方法,ramcount是生成的个数,max生成范围上限
<script>
function numbers(ramcount,max){
var flag = 1;
var output = "";
var r = new Array (ramcount);
for (var i = 1; i <= ramcount; i++) {
r[i] = Math.round(Math.random() * (max-1))+1;
}
for (var i = ramcount; i >= 1; i--) {
for (var j = ramcount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])){
flag = 0;
}
}
}
if (flag == 1) {
for (var k = 1; k <= ramcount; k++) {
output += r[k] + ",";
}
return output;
}else{
numbers(ramcount,max);
}
}
function toout(){
alert(numbers(5,10));
}
window.onload = function() {toout();}
</script> 展开
<script>
function numbers(ramcount,max){
var flag = 1;
var output = "";
var r = new Array (ramcount);
for (var i = 1; i <= ramcount; i++) {
r[i] = Math.round(Math.random() * (max-1))+1;
}
for (var i = ramcount; i >= 1; i--) {
for (var j = ramcount; j >= 1; j--) {
if ((i != j) && (r[i] == r[j])){
flag = 0;
}
}
}
if (flag == 1) {
for (var k = 1; k <= ramcount; k++) {
output += r[k] + ",";
}
return output;
}else{
numbers(ramcount,max);
}
}
function toout(){
alert(numbers(5,10));
}
window.onload = function() {toout();}
</script> 展开
1个回答
展开全部
这边测试也没搞清楚原因,只好重写了源代码。
<html>
<body>
<input type=button onclick=getnum(5,10) value=getnum>
<div id=shownum></div>
<script type="text/javascript">
function getnum(ramcount,max){
var r=new Array();
var temp;
var flag=0;
var i=0;
do{
temp=Math.round(Math.random() * (max-1))+1;
for(x in r)
{
//alert(r[x]);
tempto=r[x]-temp;
if(tempto==0){flag=1;}
}
if(flag==0){r[i]=temp;i++;}
else{flag=0}
}while(i<ramcount);
shownum.innerHTML+=r.join()+"<br>";
}
</script>
</body>
</html>
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询